[英]“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=z
, y=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.