title: [] and * operator overloading for a Rational class in c++
body: <p>I'm having difficulty trying to overload the <code>[]</code> and <code>*</code> operators. This is the given code:</p>
  
  <pre><code>#include&lt;iostream&gt;
  
  class Rational {
    public:
      Rational (int numerator=0, int denominator = 1) : n(numerator), d(denominator) { }
    private:
      int n, d;
  };
  
  std::ostream&amp; operator&lt;&lt;(std :: ostream&amp; out, const Rational&amp; r) {
    return out &lt;&lt; r[0] &lt;&lt; '/' &lt;&lt; r[1] &lt;&lt; std::endl;
  }
  
  int main() {
    Rational rat1(2,3), rat2(3,4);
  
    std::cout &lt;&lt; rat1 &lt;&lt; std::endl;
    std::cout &lt;&lt; rat1 * rat2 &lt;&lt; std::endl;
  }
  </code></pre>
  
  <p>Please overload [] and * operator for class Rational</p>
  
  <pre><code>I tried the following:
  #include&lt;iostream&gt;
  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&amp; operator*(Rational&amp; rhs){
    return *this(n*(rhs.n),d*(rhs.d));
   }
   private:
   int n,d;
  };
  std::ostream&amp; operator&lt;&lt;(std :: ostream&amp; out , const Rational&amp; r) {
   return out&lt;&lt;r[0]&lt;&lt;'/'&lt;&lt;r[1]&lt;&lt;std::endl;
  }
  int main(){
   Rational rat1(2,3) , rat2(3,4);
   std::cout&lt;&lt;rat1&lt;&lt;std::endl;
   std::cout&lt;&lt;rat1*rat2&lt;&lt;std::endl;
  }
  </code></pre>
  
  <p>After trying this I get the following errors:</p>
  
  <pre><code>error: passing ‘const Rational’ as ‘this’ argument of ‘int Rational::operator[](int)’ discards qualifiers [-fpermissive]
   return out&lt;&lt;r[0]&lt;&lt;'/'&lt;&lt;r[1]&lt;&lt;std::endl;
  
  error: passing ‘const Rational’ as ‘this’ argument of ‘int Rational::operator[](int)’ discards qualifiers [-fpermissive]
   return out&lt;&lt;r[0]&lt;&lt;'/'&lt;&lt;r[1]&lt;&lt;std::endl;
  </code></pre>
  
  <p>What am I doing wrong?</p>