Write a test case as follows:
#include<iostream>
using namespace std;
class Test
{
public:
Test &operator=(const Test&)
{
cout<<"operator="<<endl;
};
};
int main()
{
Test t1;
Test t2 = t1;
}
After execution, the result is:
It can be seen that when performing operator overloading on "=", there is no output statement executed in the operator execution overload when = is called in main
After improving it, do a test:
#include<iostream>
using namespace std;
class Test
{
public:
Test()
{
cout<<"Constructor"<<endl;
}
Test &operator=(const Test&)
{
cout<<"operator="<<endl;
};
};
int main()
{
Test t1;
Test t2 = t1;
}
After execution, the result is:
It can be seen that in Test t2 = t1; it is not the "=" assignment that is executed, but the constructor that is executed
More specifically:
#include<iostream>
using namespace std;
class Test
{
public:
Test()
{
cout<<"Constructor"<<endl;
}
Test(const Test&)
{
cout<<"Copy Constructor"<<endl;
}
Test &operator=(const Test&)
{
cout<<"operator="<<endl;
};
};
int main()
{
Test t1;
Test t2 = t1;
}
The output is:
It is found that the copy constructor is actually called, and the copy constructor will call the standard constructor again
Then the initial program should be modified as follows:
#include<iostream>
using namespace std;
class Test
{
public:
Test &operator=(const Test&)
{
cout<<"operator="<<endl;
};
};
int main()
{
Test t1;
Test t2;
t2 = t1;
}
The execution results are as follows:
So it is found that Test t2 = t1 does not perform the assignment operation, but executes the copy constructor