【问题标题】:operator overloading in c++ ( with and without friend )C++ 中的运算符重载(有和没有朋友)
【发布时间】:2010-09-30 18:01:21
【问题描述】:

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

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

希望对差异进行一些解释,谢谢!

【问题讨论】:

  • 这些声明在类中吗?
  • 您的 #2 甚至不需要成为朋友 - 它不会访问 Rational 的任何私人成员。它可以(并且应该)完全在类之外声明/定义。

标签: c++ operators operator-overloading unary-operator


【解决方案1】:

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

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

 // 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;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 2016-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多