gpt4 book ai didi

c++ - 为什么返回 const Rational 而不是 Rational

转载 作者:可可西里 更新时间:2023-11-01 17:06:09 24 4
gpt4 key购买 nike

看到operator*的实现如下:

class Rational {
public:
Rational(int numerator=0, int denominator=1);
...
private:
int n, d; // numerator and denominator
friend const Rational operator*(const Rational& lhs, const Rational& rhs)
{
return Rational(lhs.n * rhs.n, lhs.d * rhs.d);
}
};

这里有两个问题:

  • Q1> 为什么运营商*必须返回const 有理而不是简单理性的
  • Q2>定义友元函数时,是否应该关心访问修饰符?

最佳答案

  1. 这样你就不能做像Rational a, b, c这样的事情了; (a * b) = c;

  2. 没有。

关于c++ - 为什么返回 const Rational 而不是 Rational,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3989641/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com