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