为什么返回*会导致无限循环?

Aqu*_*irl 3 c++ operator-overloading this

class binaryOperators 
{
    public:
        int i;

        binaryOperators (int tempI = 0)
        {
            i = tempI;
        }

        binaryOperators operator+ (const binaryOperators &right);
};
Run Code Online (Sandbox Code Playgroud)
binaryOperators binaryOperators :: operator+ (const binaryOperators &right)
{
    return binaryOperators (*this + right.i);
}

binaryOperators operator+ (const binaryOperators &left, const binaryOperators &right)
{
    return binaryOperators (left.i + right.i);
}

int main ()
{
    binaryOperators obj (10);

    obj = 11 + obj;

    obj = obj + 11;

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

所以,这里的语句obj = 11 + obj;使用显式参数规范调用函数.并且这个obj = obj + 11;调用作为类成员的函数.精细.

问题是第二次调用导致无限循环.是什么原因以及如何避免这种情况?

zen*_*hoy 9

问题出在声明中:

return binaryOperators (*this + right.i);
Run Code Online (Sandbox Code Playgroud)

*this 是binaryOperators类型,因此需要一个带有左侧参数类型(或引用)binaryOperators的运算符.

可能匹配的运算符是您提供的两个运算符,因此右侧参数必须是类型const binaryOperators &.因此,right.i使用适当的构造函数将其转换为临时binaryOperators.

结果,成员操作符最终调用自身,调用自身,调用自身等,导致无限递归(您看作无限循环).

您可以通过以下方式解决此问题:

return binaryOperators (this->i + right.i);
Run Code Online (Sandbox Code Playgroud)


thi*_*ton 5

binaryOperators::i(类型int)转换binaryOperators为隐式(即未声明explicit).

return binaryOperators (*this + right.i); // (1)
binaryOperators binaryOperators :: operator+ (const binaryOperators &right); // (2)
binaryOperators operator+ (const binaryOperators &left, const binaryOperators &right); // (3)
Run Code Online (Sandbox Code Playgroud)

在第(1)行operator+中,可以考虑两个函数:成员版本(2)和免费版本(3).由于LHS属于类型binaryOperators&,因此会员版本适用且首选.它的参数是类型const binaryOperators &,并且第(1)行中给出的参数是类型int,因此编译器尝试转换intconst binaryOperators &.

由于存在非explicit使用一个参数的构造函数,它被用作从隐式转换intconst binaryOperators &.现在我们有类型的两个操作数binaryOperators&const binaryOperators &时,operator+在(2)可以被调用,我们是对我们开始的地方.

经验教训:不要过度隐式转换.