c++ 中的运算符重载(有朋友和没有朋友)
嘿,我想知道这两个运算符定义之间的区别:
1:
class Rational{
//...
public:
//...
Rational operator -() const{ return Rational(-t,b);}
//...
};
2:
class Rational{
//...
public:
//...
friend Rational operator -(const Rational& v) {return Rational(-t,b);}
//...
};
据我了解,对于以下用法:
Rational s = -r
r.operator-() // should happen
希望对差异进行一些解释,谢谢!
Hey, I would like to know the difference between these 2 operator definitions:
1:
class Rational{
//...
public:
//...
Rational operator -() const{ return Rational(-t,b);}
//...
};
2:
class Rational{
//...
public:
//...
friend Rational operator -(const Rational& v) {return Rational(-t,b);}
//...
};
as far as i understand, for the usage of:
Rational s = -r
r.operator-() // should happen
would like some explenation for the difference, thanks !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在大多数情况下,它们是相同的。
首先,我觉得你写的都不对。它们应该是:
主要区别在于,如果您有另一种可转换为 Rational 对象的类型(例如
MyRational
),那么:将适用于第二个定义,但不适用于第一个定义。
For the most part, they are the same.
First of all, I don't think you have either written right. They should be:
The major difference is that if you have another type (say
MyRational
) which is convertible to a Rational object, then:will work with the second definition, but not for the first.