c++类运算符重载遇到的函数形参问题

时间:2023-03-09 04:17:58
c++类运算符重载遇到的函数形参问题
class A
{
public:
A(int arg1, int arg2);
~A();
A &operator = ( A &other);
A operator + ( A &other);
private:
int a, b; }; A::A(int arg1, int arg2)
{
a = arg1;
b = arg2;
} A::~A()
{ }
A &A::operator=( A &other)
{
if (this == &other)
{
return *this;
} this->a = other.a;
this->b = other.b;
return *this;
} A A::operator+( A &other)
{
return A(a+other.a, b+other.b);
// return other;
}

上面的这个类中重载了=和+号运算符, 但是参数都是引用,而不是const的引用,这样在遇到形如

A a(1, 2);

a + A(3, 4);

的运算时就会出现错误,原因如下:

a + A(3, 4)等价于a.operator +(A(3, 4))

这里要提到的是函数的返回值不能作为左值(可以参见http://blog.****.net/sunshinewave/article/details/7830701

但是类中的函数声明确是

A operator + ( A &other)

说明other在函数中是可以修改的,这就产生了矛盾,所以编译器会提示无法把A类型的变量转换成A&的错误提示

总结:在类中重载运算符时要把形参表示为const A&的形式,不仅为了减少开销