重载++和+运算符

vic*_*ico 0 c++

为什么我可以++在LHS和RHS中重载并使用运算符,而+只能在LHS模式下工作?

class B {
public:

    string operator ++ () { return "hello"; }
    string operator + () {  return "hello2"; }
};

int main ()
{
    B b;
    string s = +b ;
    s = b+ ; // compile error syntax error : ';'    

    s = b++; 
    s = ++b;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*our 6

重载运算符只能使用与相应内置运算符相同的语法.内置++定义为前缀或后缀运算符; 内置+函数只被定义为前缀运算符(当然还有二元运算符).

请注意,即使没有该b+行,您的代码也无法编译,因为您缺少后缀版本++:

string operator ++ (int) { return "postfix"; }
Run Code Online (Sandbox Code Playgroud)