ccsun1 :oop % ccsun1 :oop % cat -n bin.cpp 1 //a simple class for binary number 2 #include 3 class BIN{ 4 long data; 5 friend ostream& operator<< (ostream&, const BIN&); 6 public: 7 BIN(){data=0;}; 8 BIN(long); 9 BIN(BIN& x) // copy constructor 10 { cout << "(copy)"; // data = x.data; 11 } 12 }; 13 BIN::BIN(long x) { data=x; } 14 int main() 15 { 16 long m; 17 BIN y; 18 m=126; 19 y=m; 20 cout << "m=" << m; 21 cout << "=== y =" << y << endl;; 22 BIN x=y; // will call copy constructor 23 cout << "\t x= " << x << " Note\n"; 24 cout << "What if the copy constructor is removed?\n\n"; 25 while(m){ 26 cout << "Input an integer:"; 27 cin >> m; 28 cout << "===" << (BIN)m; 29 cout << " = " << m << endl; 30 } 31 cout << "Thank you for using AT&T:-)\n"; 32 } 33 ostream& operator<< (ostream& oo, const BIN& x) 34 { 35 long tmp,i; 36 tmp = x.data; 37 for(i=1; i<=32; i++){ 38 if(tmp<0) oo << 1; 39 else oo << 0; 40 if(i%4 == 0) cout << " "; // Ohh .. bug? 41 tmp = tmp << 1; 42 } 43 return oo; 44 } ccsun1 :oop % g++ bin.cpp ccsun1 :oop % ./a.out m=126=== y =0000 0000 0000 0000 0000 0000 0111 1110 (copy) x= 0000 0000 0000 0000 0000 0000 0000 0000 Note What if the copy constructor is removed? Input an integer:3 ===0000 0000 0000 0000 0000 0000 0000 0011 = 3 Input an integer:127 ===0000 0000 0000 0000 0000 0000 0111 1111 = 127 Input an integer:128 ===0000 0000 0000 0000 0000 0000 1000 0000 = 128 Input an integer:256 ===0000 0000 0000 0000 0000 0001 0000 0000 = 256 Input an integer:-1 ===1111 1111 1111 1111 1111 1111 1111 1111 = -1 Input an integer:-2 ===1111 1111 1111 1111 1111 1111 1111 1110 = -2 Input an integer:0 ===0000 0000 0000 0000 0000 0000 0000 0000 = 0 Thank you for using AT&T:-) ccsun1 :oop % ccsun1 :oop % exit