您的位置:首页 > 其它

使用引用成员变量

2010-03-12 13:44 190 查看
类的成员中有引用成员变量时,

默认的=函数无法完成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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: