When we see the "=" operator, we think it is necessary to call the value assignment function. However, in the following example, Statement a B = c shows that the copy constructor is called.
Conclusion: when the "=" operator is assigned a value to an object, if it appears during object definition, the copy constructor is called. If it is not, B = d In the example, the value assignment function.
# Include <iostream>
Using namespace std;
Class
{
Public:
A (int d ):
Data (d)
{};
A (const a & aa );
A & operator = (const a & aa );
Void show ();
Private:
Int data;
};
A: a (const a & aa)
{
Cout <"copy constructor" <endl;
Data = aa. data;
// Return * this;
};
A & a: operator = (const a & aa)
{
Cout <"assignment" <endl;
If (this = & aa)
Return * this;
Data = aa. data;
Return * this;
};
Int main ()
{
A c (1 );
A d (2 );
A B = c; // value assignment function? Or copy the constructor?
B = d;
Return 0;
}
Running result
[Root @ localhost tmpc ++] #./s1
Copy constructor
Assignment