简体   繁体   English

“ return * this”赋值运算符重载

[英]“return *this” assignment operator overloading

Fraction& Fraction::operator= (const Fraction &fraction)
{
    // do the copy
    m_numerator = fraction.m_numerator;
    m_denominator = fraction.m_denominator;

    return *this;
}

int main()
{
    Fraction fiveThirds(5, 3);
    Fraction f;
    f = fiveThirds; // calls overloaded assignment
    std::cout << f;

    return 0;
}

I have some problems with the concept of return this when overloading the assignment operator. 重载赋值运算符时,我有一些关于return this的概念的问题。

In the main function f = fiveThirds will call the assignment operator, and it will return *this , ie return a Fraction object! 在主函数中, f = fiveThirds将调用赋值运算符,并将返回*this ,即返回一个Fraction对象!

The problem is f = fiveThirds will return the object, but there isn't any Fraction object to receive it! 问题是f = fiveThirds将返回该对象,但是没有任何小数部分对象可以接收它!

In the assignment chain x=y=z , y=z will return an object ( k ) which will be assigned to x , however x=k will also return an object, so who receives this object? 分配链 x=y=zy=z将返回一个对象( k ),该对象将被分配给x ,但是x=k还将返回一个对象,那么谁接收这个对象?

I've done my best to describe my problem. 我已经尽力描述了我的问题。

The problem is f = fiveThirds will return the object, but there isn't any Fraction object to receive it! 问题是f = fourThirds将返回该对象,但是没有任何小数部分对象可以接收它!

More accurately, it returns a reference to an object. 更准确地说,它返回对对象的引用。

so who receives this object? 那么谁收到这个物体呢?

The return value is discarded. 返回值将被丢弃。

There is no problem. 没有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM