类的成员中有引用成员变量时,
默认的=函数无法完成copy,因而编译器不再生成,
参见下面的代码,
编译错误C2582,
这时候补上A& operator = (A& rhs) ,
就没问题了。
#include <iostream> #include <typeinfo> using namespace std; class A { public: A(int n) : x(n), y(x) { } int x; int& y; void print() { cout << "---------------------" <<endl; cout <<x <<endl; cout <<y <<endl; } //A& operator = (A& rhs) //{ // this->x = rhs.x; // return *this; //} }; int main () { A a1(8); A a2(9); a1.print(); a2.print(); a1 = a2; //error C2582: 'operator =' function is unavailable in 'A' a1.print(); a2.print(); return 0; }