标签:
赋值操作为什么要返回 reference to *this? 要弄清这个问题之前,先了解函数的返回值类型:返回值类型,返回引用类型
test operator= (const test &t)
{
...
cout << "赋值" << endl;
return *this;
}
test &operator= (const test &t)
{
...
cout << "赋值" << endl;
return *this;
}
class test
{
public:
test() :i(10)
{
cout << "构造" << endl;
}
~test()
{
}
test(const test &t)
{
this->i = t.i;
cout << "拷贝" << endl;
}
test operator= (const test &t)
{
i = t.i;
cout << "赋值" << endl;
return *this;
}
void setData(int value)
{
i = value;
}
int getData()
{
return i;
}
private:
int i;
};
int _tmain(int argc, _TCHAR* argv[])
{
test a;
test b;
test c;
cout << a.getData() << endl << b.getData() << endl<<c.getData() << endl;
a.setData(20);
c = b= a;
cout << a.getData() << endl << b.getData() << endl << c.getData() << endl;
return 0;
}
C++ 赋值函数为什么返回reference to *this?
标签:
原文地址:http://www.cnblogs.com/chengkeke/p/5417359.html