//a simple class for binary number by tsaiwn@csie.nctu.edu.tw #include #include using namespace std; class BIN{ protected: long data; // so that can be accessed by derived class friend ostream& operator<< (ostream&, const BIN&); public: BIN(){data=0;}; BIN(long); BIN(const BIN& x) // copy constructor { data = 3; cout << "(copy)"; // data = x.data; } }; BIN::BIN(long x) { data=x; } // new class inherit from BIN (i.e., we reuse BIN to build a new class) class BINREAL: public BIN{ float fdata; public: BINREAL(){data=0; setBin( ); }; BINREAL(float x) { fdata=x; setBin( ); } void setBin( ) { long * ptemp = (long *) &fdata; data = *ptemp; // data = ptemp[0]; } }; int main() { float m; BINREAL y; m=1234567.3; // actually it is 1234567.25 y=m; cout << "m=" << setprecision(12) << setw(12) << m; cout << "=== y =" << y << endl;; BIN x=y; // will call copy constructor cout << "\t\t x= " << x << " Note\n"; cout << "What if the copy constructor is removed?\n\n"; while(m){ cout << "Input a float number: "; cin >> m; y = m; cout << "===" << y; cout << " = " << m << endl; } cout << "Thank you for using AT&T:-)\n"; } ostream& operator<< (ostream& oo, const BIN& x) { long tmp,i; tmp = x.data; for(i=1; i<=32; i++){ if(tmp<0) oo << 1; else oo << 0; if(i%4 == 0) oo << " "; // OK now tmp = tmp << 1; } return oo; } /*** answer: 10:24am magpie::oop/> g++ binfloat.cpp 10:25am magpie::oop/> ./a.out m= 1234567.25=== y =0100 1001 1001 0110 1011 0100 0011 1010 (copy) x= 0000 0000 0000 0000 0000 0000 0000 0011 Note What if the copy constructor is removed? Input a float number: 1234567.2 ===0100 1001 1001 0110 1011 0100 0011 1010 = 1234567.25 Input a float number: 1234567.3 ===0100 1001 1001 0110 1011 0100 0011 1010 = 1234567.25 Input a float number: 0.25 ===0011 1110 1000 0000 0000 0000 0000 0000 = 0.25 Input a float number: 0.5 ===0011 1111 0000 0000 0000 0000 0000 0000 = 0.5 Input a float number: 1.25 ===0011 1111 1010 0000 0000 0000 0000 0000 = 1.25 Input a float number: 1.75 ===0011 1111 1110 0000 0000 0000 0000 0000 = 1.75 Input a float number: 1.875 ===0011 1111 1111 0000 0000 0000 0000 0000 = 1.875 Input a float number: 0 ===0000 0000 0000 0000 0000 0000 0000 0000 = 0 Thank you for using AT&T:-) 10:26am magpie::oop/> *******************/