jas*_*ine 3 c++ operator-overloading
请考虑以下代码:
class A
{
public:
A& operator=( const A& );
const A& operator+( const A& );
const A& operator+( int m );
};
int main()
{
A a;
a = ( a + a ) + 5; // error: binary '+' : no operator found which takes a left-hand operand of type 'const A'
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以解释为什么上面的错误返回?
" ( a + a )"调用" const A& operator+( const A& )"并返回一个常量引用,const A& operator+( int m )如果我没有弄错,则将其传递给" ".
如何修复上述错误(不创建全局二元运算符+或接受int的构造函数),以main()允许内部语句?
如果我没有弄错的话,然后将其传递给"const A&operator +(int m)"
不可以.由于LHS是一个const A&而RHS是一个int,它会打电话给*
[anyType] operator+ (int rhs) const
// ^^^^^ note the const here.
Run Code Online (Sandbox Code Playgroud)
因为你只提供了非const版本const A& operator+( int m ),编译器会抱怨.
*:或者operator+(const int& rhs) const或者operator+(float rhs) const......最关键的一点是,它必须是一个const方法.
operator+ 应该返回一个实例,而不是一个引用:
// as member function
A operator+(const A& other);
// as free function
A operator+(const A& left, const A& right);
Run Code Online (Sandbox Code Playgroud)
解释具体问题是"返回一个常量引用然后传递给const A& operator+( int m )".由于你有一个const引用,它不能调用该函数,因为它不是const方法(即const A& operator+( int m ) const).
那就是说,这不是解决问题的方法operator+.如果你要返回一个引用,它的引用是什么?运算符+中的本地会很糟糕,因为您不应该返回对本地的引用.对全局的引用会很糟糕,因为它会限制代码的正确使用方式.对分配的内存的引用会很糟糕,因为它会泄漏内存.引用*this会很糟糕,因为那样operator+表现得像operator +=.