復制也是用的=運算符瘪吏,那么什么時候是復制構造器蔑祟,什么適合是調用運算符=重載毒涧?
用其他對象定義新對象的時候是復制構造器,如下:
A a2(a1);
A a3 = a2;
在已經定義好后徙邻,用=進行賦值的是調用運算符=重載
class A {
private:
int m_elem;
public:
A() {
std::cout << "This is construction!" << std::endl;
}
A(const A& others) {
std::cout << "This is copy construction!" << std::endl;
}
void operator=(const A& others) {
std::cout << "This is operator == override!" << std::endl;
}
};
int main()
{
A a1; //This is construction!
A a2(a1); //This is copy construction!
A a3 = a2; //This is copy construction!
a1 = a2; //This is operator == override!