我们先来看一个简单测程序:
#include <iostream>
using namespace std;
class A
{
private:
int x;
public:
A()
{
}
A(int xx)
{
x = xx;
}
int get() const
{
return x;
}
void operator=(const A &a)
{
x = a.x;
}
};
int main()
{
A a, b, c(1);
// ok
b = c;
a = b;
cout << a.get() << endl;
cout << b.get() << endl;
cout << c.get() << endl;
// error, 没法支持连续赋值
a = b = c;
cout << a.get() << endl;
cout << b.get() << endl;
cout << c.get() << endl;
return 0;
}
上面程序最大的问题在于不支持连续链式赋值, 更更改为:
#include <iostream>
using namespace std;
class A
{
private:
int x;
public:
A()
{
}
A(int xx)
{
x = xx;
}
int get() const
{
return x;
}
A operator=(const A &a) // ok, but not perfect
{
x = a.x;
return *this;
}
};
int main()
{
A a, b, c(1);
// ok
a = b = c;
cout << a.get() << endl;
cout << b.get() << endl;
cout << c.get() << endl;
return 0;
}
结果为:
1
1
1
虽然结果正确, 但是, 在返回的时候, 会有对象的拷贝, 有额外的消耗, 所以最好返回引用, 如下:
#include <iostream>
using namespace std;
class A
{
private:
int x;
public:
A()
{
}
A(int xx)
{
x = xx;
}
int get() const
{
return x;
}
A& operator=(const A &a) // perfect
{
x = a.x;
return *this;
}
};
int main()
{
A a, b, c(1);
// ok
a = b = c;
cout << a.get() << endl;
cout << b.get() << endl;
cout << c.get() << endl;
return 0;
}
程序的结果为:
1
1
1
实际上, C++的很多内置类型和STL库都是这样的。 其实, 除了operator=之外, operator+=也类似。比如:
#include <iostream>
using namespace std;
class A
{
private:
int x;
public:
A()
{
}
A(int xx)
{
x = xx;
}
int get() const
{
return x;
}
A& operator+=(const A &a) // perfect
{
x += a.x;
return *this;
}
};
int main()
{
A a(1), b(1), c(1);
// ok
a += b += c;
cout << a.get() << endl;
cout << b.get() << endl;
cout << c.get() << endl;
return 0;
}
结果如下:
3
2
1
好吧, 本文就先学习到这里了, 最后再次看一眼:Effective C++ 条款10: 令operator= 返回一个reference to *this.
哦, 对了, 差点忘记说:上述的opertor=函数其实不够perfect, 还有隐患, 需要处理“自我赋值”, 我们将会在后续博文中考虑这一点。