在c ++中为Rational类重载[]和*运算符

时间:2015-09-27 20:17:59

标签: overloading operator-keyword

我在尝试重载[]*运算符时遇到了困难。这是给定的代码:

#include<iostream>

class Rational {
  public:
    Rational (int numerator=0, int denominator = 1) : n(numerator), d(denominator) { }
  private:
    int n, d;
};

std::ostream& operator<<(std :: ostream& out, const Rational& r) {
  return out << r[0] << '/' << r[1] << std::endl;
}

int main() {
  Rational rat1(2,3), rat2(3,4);

  std::cout << rat1 << std::endl;
  std::cout << rat1 * rat2 << std::endl;
}

请为Rational类

重载[]和*运算符
I tried the following:
#include<iostream>
class Rational {
 public:
 Rational (int numerator=0 , int denominator = 1) :
 n(numerator),d(denominator)
 { }
 int operator[](int i){
  if(i==0)
   return n;
   else return d;
  }
 Rational& operator*(Rational& rhs){
  return *this(n*(rhs.n),d*(rhs.d));
 }
 private:
 int n,d;
};
std::ostream& operator<<(std :: ostream& out , const Rational& r) {
 return out<<r[0]<<'/'<<r[1]<<std::endl;
}
int main(){
 Rational rat1(2,3) , rat2(3,4);
 std::cout<<rat1<<std::endl;
 std::cout<<rat1*rat2<<std::endl;
}

尝试此操作后,我收到以下错误:

error: passing ‘const Rational’ as ‘this’ argument of ‘int Rational::operator[](int)’ discards qualifiers [-fpermissive]
 return out<<r[0]<<'/'<<r[1]<<std::endl;

error: passing ‘const Rational’ as ‘this’ argument of ‘int Rational::operator[](int)’ discards qualifiers [-fpermissive]
 return out<<r[0]<<'/'<<r[1]<<std::endl;

我做错了什么?

1 个答案:

答案 0 :(得分:0)

问题在于这一行:

.focus-item {
    display: flex;
}

.item {
    display: flex;
    flex: 1 1 50%;
}

.focus-item-1 {
    flex-direction: column;
    align-items: flex-end;
}

应该是

return *this(n * (rhs.n), d * (rhs.d));

您需要通过调用构造函数来创建并返回一个新的return * new Rational(n * rhs.n, d * rhs.d); ,这永远不会通过Rational指针完成。

您还应该验证输入:this应该生成错误。