【问题标题】:How to overload operator+ if the calling object is not a class object?如果调用对象不是类对象,如何重载 operator+?
【发布时间】:2018-02-24 22:14:39
【问题描述】:
Class fraction
{
public:
      fraction operator+ (const fraction& fr) const;
private:
      int num; //numerator 
      int den; //denominator
};

我想重载 operator+ 以便它执行整数常量(调用对象)和分数的乘法。

fraction fraction::operator+ (const fraction& fr) const
{
    fraction result;

    result.num = fr.num + fr.den * (*this);
    //error message says invalid operands to binary exprssion ('int' and 'constant fraction')
    result.den = fr.den;

    simplified_fr(result); // a helper function to simplify the resulted fraction 
    return result;
}

问题似乎与调用对象的类型有关。我打算使它成为一个常数整数,但计算机认为它是一个“常数分数”。有人可以告诉我为什么会发生这种情况,我该如何解决?提前谢谢!!!

【问题讨论】:

  • 这个new_fr.num = fr.num * (*this); 毫无意义,你想在实现中做一些int 算术而不是fractionresult.den = fr.den; 这在数学上是错误的。
  • this->num 而不是(*this)?我还可以建议潜入std::ratio吗?
  • hmm,num 是类对象的成员。但是指向的调用对象“this”应该是一个整数。所以,我不太明白 'this->num' 是如何工作的?

标签: c++ operator-overloading


【解决方案1】:

我假设你想要实现这样的目标:

fraction fract;
fraction fract2 = 2 + fract;

答案是不能为非类对象重载成员方法 operator+。但是您可以定义/重载全局 operator+ 函数:

fraction operator+(int num, const fraction& rFrac)
{
//your implementation
}

您可能需要访问fraction 类的私有成员。这可以通过让 operator+ 成为朋友来完成:

class fraction
{
    //...
    friend fraction operator+(int num, const fraction& rFrac);
    //...
}

【讨论】:

  • 顺便说一句,友元函数可以直接使用类的辅助方法吗?
  • @PhyllisQu 取决于,朋友的意思是该函数可以看到该类的私有内容,仅此而已。所以operator+可以使用私有静态方法和静态变量。它还可以在类的实例上调用私有成员方法。但它没有隐式的this 指针,因为它不是在实例上调用的。
  • 我明白了!谢谢!!
猜你喜欢
  • 2017-04-07
  • 1970-01-01
  • 2012-11-28
  • 1970-01-01
  • 2012-11-08
  • 1970-01-01
  • 1970-01-01
  • 2014-12-23
  • 2021-07-06
相关资源
最近更新 更多