看以下例子:
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容易用些。
本文通过一个C++中的Rational类实例,探讨了成员函数重载运算符*的过程及注意事项,特别是const限定符的影响。
1450

被折叠的 条评论
为什么被折叠?



