I wrote a simple C ++ class example with 1 constructor without parameters, 1 pair constructor, 2 copy constructors, 1 assignment operator and 1 plus operator.
class Complex { protected: float real, img; public: Complex () : real(0), img(0) { cout << "Default constructor\n"; } Complex (float a, float b) { cout << "Param constructor" << a << " " << b << endl; real = a; img = b; } // 2 copy constructors Complex( const Complex& other ) { cout << "1st copy constructor " << other.real << " " << other.img << endl; real = other.real; img = other.img; } Complex( Complex& other ) { cout << "2nd copy constructor " << other.real << " " << other.img << endl; real = other.real; img = other.img; } // assignment overloading operator void operator= (const Complex& other) { cout << "assignment operator " << other.real << " " << other.img << endl; real = other.real; img = other.img; } // plus overloading operator Complex operator+ (const Complex& other) { cout << "plus operator " << other.real << " " << other.img << endl; float a = real + other.real; float b = img + other.img; return Complex(a, b); } float getReal () { return real; } float getImg () { return img; } };
I used this class mainly like this:
int main() { Complex a(1,5); Complex b(5,7); Complex c = a+b;
The result is printed as:
Param constructor 1 5 Param constructor 5 7 plus operator 5 7 Param constructor 6 12
I think the copy constructor should be used in Statement 1, but I really don't know which one is being called. Please tell me who and why? Many thanks
fatpipp
source share