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()
{
}
{
if (this == &other)
{
return *this;
}
this->a = other.a;
this->b = other.b;
return *this;
}
{
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.csdn.net/sunshinewave/article/details/7830701)
但是類中的函數聲明確是
A operator + ( A &other)
說明other在函數中是可以修改的,這就產生了矛盾,所以編譯器會提示無法把A類型的變量轉換成A&的錯誤提示
總結:在類中重載運算符時要把形參表示為const A&的形式,不僅為了減少開銷