复制也是用的=运算符,那么什么时候是复制构造器,什么适合是调用运算符=重载?
用其他对象定义新对象的时候是复制构造器,如下:
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!