为什么返回 *this 会导致无限循环? [英] Why does returning *this result in an infinite loop?

查看:81
本文介绍了为什么返回 *this 会导致无限循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class binaryOperators 
{
    public:
        int i;

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

        binaryOperators operator+ (const binaryOperators &right);
};

<小时>

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;
}

因此,这里的语句 obj = 11 + obj; 调用具有显式参数规范的函数.而这个 obj = obj + 11; 调用作为类成员的函数.美好的.

So, here the statement obj = 11 + obj; calls the function with explicit argument specification. and this one obj = obj + 11; calls the function which is the member of the class. Fine.

问题是第二次调用会导致无限循环.原因是什么?如何避免?

推荐答案

binaryOperators::i(int 类型)到 binaryOperators 的转换code> 是隐式的(即未声明explicit).

The conversion from binaryOperators::i (of type int) to binaryOperators is implicit (i.e. not declared explicit).

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

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

In the line (1) two operator+ functions can be considered: The member version (2) and the free version (3). Since the LHS is of type binaryOperators&, the member version is applicable and preferred. Its argument is of type const binaryOperators &, and the argument given in line (1) is of type int, so the compiler tries to convert int to const binaryOperators &.

因为有一个带有一个参数的非explicit构造函数,它被用作从intconst binaryOperators &的隐式转换.现在我们有两个类型为binaryOperators&const binaryOperators&的操作数,可以调用(2)中的operator+,我们是对的我们从哪里开始.

Since there is a non-explicit constructor with one argument, it is used as an implicit conversion from int to const binaryOperators &. Now we have two operands of types binaryOperators& and const binaryOperators &, the operator+ in (2) can be called, and we are right where we started.

教训:不要过度进行隐式转换.

Lesson: Don't over-do implicit conversions.

这篇关于为什么返回 *this 会导致无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆