// = 赋值重载 // 注意 = 重载时,可能会调用类本身的拷贝构造函数。如果左值是没有创建的对象时, // 会调用类的拷贝构造函数 #include #include #include using namespace std; class A { private: int x; public: A(int x) : x(x) { cout << "A(int x)" << endl; } A(const A &obj) { cout << "A(A &obj)" << endl; this->x = obj.x; } A &operator=(const A &other) { cout << "A &operator=(A&other)" << endl; this->x = other.x; return *this; } public: void show() { cout << "x = " << x << endl; } }; int main() { A a1(100), a2(200); A a4 = 300; // A(300) a4 = 400; // operator=() A a3 = a1; // A(a1) a3.show(); a3 = a2; // operator=() 调用赋值重载函数 a3.show(); a3 = a4; a3.show(); return 0; }