C++对于运算符*或者+等的重载,函数返回对象需要加const吗?

本文通过一个C++中的Rational类实例,探讨了成员函数重载运算符*的过程及注意事项,特别是const限定符的影响。

    看以下例子:

class Rational
{
public:
  Rational(int numerator = 0, int denominator = 1);
  Rational(const Rational &rhs);

  int getN() const{return n;}
  int getN() {return n;}
  int getD() const{return d;}
  int getD() {return d;}

  const Rational operator*(const Rational& lhs)
  {
    return Rational(this->n * lhs.getN(), this->d * lhs.getD());
  }
private:
  int n, d;              // numerator and denominator
};

Rational::Rational(int numerator, int denominator)
    : n(numerator)
    , d(denominator)
{
    qDebug() << "structor" << numerator << denominator;
}

Rational::Rational(const Rational &rhs)
    : n(rhs.getN())
    , d(rhs.getD())
{
    qDebug() << "copy structor";
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    Rational x(1, 2);
    Rational y(1, 2);
    Rational z(1, 2);
    Rational m = x * y *z;
    qDebug() << m.getN() << m.getD();

    return a.exec();
}

 


运算符*的重载返回值没有加上const,运行正确,见图。

如果加上了const后,会怎样呢?
\main.cpp:13: error: passing 'const Rational' as 'this' argument of 'const Rational Rational::operator*(const Rational&)' discards qualifiers
我们可以修改一下:Rational m = x * (y *z);
执行ok。

从执行结果来看,这种重载方式还是不使用const容易用些。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值