理解临时对象超载" /"操作者

时间:2014-05-23 10:50:58

标签: c++

我试着理解这个代码在blow c ++程序中是怎样的,我的问题是

  

返回Rational(_n * rhs._d,_d * rhs._n);

  1. _n如何引用第一个对象数据成员?
  2. 临时对象如何引用获取a._n?
  3. C ++程序:

    #include <iostream>
    
    class Rational {
        int _n;
        int _d;
    public:
        Rational ( int numerator = 0, int denominator = 1 ) : _n(numerator), _d(denominator) {};
        Rational ( const Rational & rhs ) : _n(rhs._n), _d(rhs._d) {};  // copy constructor
        inline int numerator() const { return _n; };
        inline int denominator() const { return _d; };
        Rational operator / ( const Rational & ) const;
    };
    
    Rational Rational::operator / ( const Rational & rhs ) const {
        return Rational(_n * rhs._d, _d * rhs._n);
    }
    // useful for std::cout
    std::ostream & operator << (std::ostream & o, const Rational & r) {
        return o << r.numerator() << '/' << r.denominator();
    }
    
    int main( int argc, char ** argv ) {
        using namespace std;
    
        Rational a = 7;     // 7/1
        Rational b(5, 3);   // 5/3
        cout <<"a is : " <<a << endl;
        cout << " b is : "<< b << endl;
        cout << " a/b is:  "<< a / b << endl;
    
        return 0;
    }
    

    其中有

      

    a是:7/1
      b是:5/3
      a / b是:21/5

    此程序是github

    中此程序的简单版本

1 个答案:

答案 0 :(得分:1)

用几句话来说,operator /可以这样写:

class Rational
{
    //...rest of the stuff:

    Rational Divide( const Rational & rhs) const
    {
        return Rational(_n * rhs._d, _d * rhs._n);
    }
};

而不是operator /代替result = a/b,您可以写result = a.Divide(b) 基本上operator /的行为方式与Divide方法相同:

现在,让我们分析一下划分方法:

你有:

result = a.Divide(b); // which is the same as result = a/b in your case

Rational Divide( const Rational & rhs) const
{
    return Rational(_n * rhs._d, _d * rhs._n);
}
  • rhs是传递给Divide的参数,它是变量b

  • _n_d是变量a的成员。您也可以这样写:this->_nthis->_dDivide是会员功能,因此可以直接访问_n_d

现在为了进一步简化它以理解它的工作方式,这是另一种写这个的方法:

class Radional {/*stuff*/};

Rational Divide( const Rational & a, const Rational & b)
{
    return Rational(a._n * b._d, a._d * b._n);
}

对于此示例,result = a.Divide(b)转换为result = Divide(a,b) 请注意,现在您有a._na._d这是函数Divide的第一个参数

作为结论,表达式a/b只是编写c ++标准允许的Divide(a,b)的一种非常好的方式。