![](/img/trans.png)
[英]How can i call a operator overloaded member function(or use the operator) from another operator overloading member function in the same class?
[英]Can I only have const overloaded operator member function?
我正在实现一个分数类,并且需要重载算术运算符。 问题是,我只能实现const
版本。
例如,加法:
Fraction operator+( const Fraction& other ) const;
由于非const对象和const Fraction对象都可以调用此函数,因此我仍然需要非const operator+
成员函数吗?
可以在非const
对象上调用const
成员函数,因此不,您不需要非const
重载。
Fraction a, b;
Fraction c = a + b; // no problem
通常,使用member operator+=
和nonmember operator+
可以更好地解决此类问题,如下所示:
class Fraction {
public:
const Fraction& operator+=(const Fraction&);
};
Fraction operator+(const Fraction& lhs, const Fraction& rhs) {
Fraction res(lhs);
res += rhs;
return res;
}
可以。您可以在非const
对象上调用const
方法,就像将const
引用绑定到非const
对象一样。 IOW,您始终可以将可以修改的对象传递给承诺不对其进行修改的代码-不存在安全损失。 相反,这是不正确的-如果您有const
对象(=>您承诺不会修改的对象),则无法将其传递给不遵守此承诺的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.