c++ 中的运算符重载(有朋友和没有朋友)

发布于 2024-09-25 18:24:37 字数 443 浏览 2 评论 0原文

嘿,我想知道这两个运算符定义之间的区别:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

与他有关 2024-10-02 18:24:37

在大多数情况下,它们是相同的。

首先,我觉得你写的都不对。它们应该是:

 // Member function.      "-r" calls r.operator-() 
 Rational Rational::operator -() const{ return Rational(-t,b);} 

 // (technically a) global function.   "-r"  calls ::operator-(r) 
 friend Rational operator -(const Rational& v) {return Rational(-v.t,v.b);} 

主要区别在于,如果您有另一种可转换为 Rational 对象的类型(例如 MyRational),那么:

  MyRational mr = MyRational();
  Rational r = -mr;

将适用于第二个定义,但不适用于第一个定义。

For the most part, they are the same.

First of all, I don't think you have either written right. They should be:

 // Member function.      "-r" calls r.operator-() 
 Rational Rational::operator -() const{ return Rational(-t,b);} 

 // (technically a) global function.   "-r"  calls ::operator-(r) 
 friend Rational operator -(const Rational& v) {return Rational(-v.t,v.b);} 

The major difference is that if you have another type (say MyRational) which is convertible to a Rational object, then:

  MyRational mr = MyRational();
  Rational r = -mr;

will work with the second definition, but not for the first.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文