gpt4 book ai didi

c++ - 在 C++ 中扩展运算符重载

转载 作者:行者123 更新时间:2023-11-30 02:58:35 25 4
gpt4 key购买 nike

我是 C++ 的新手(我一生都在 C 中度过,所以我认为是时候花一些时间学习一门新语言以丰富我的知识 :) )。我有一个名为“Rational”的类,我有它的所有特定函数,用于 getter、setter、构造函数等(这里不相关)。有趣的部分是当我尝试重载 +、-、、/运算符时。我能够在两个 Rational 对象之间成功地做到这一点,例如 Rational a(1,5),b(5,5),c; c = a + b;所以这一切都很好。现在我正在尝试通过在有理数和整数之间尝试 +、-、、/来升级我的类(class),例如 2 + a、10 - b 等。这是我的重载代码的(片段)有理数之间:

理性.cc

...
Rational Rational::operator+(Rational B) {
int Num;
int Den;

Num = p * B.q + q * B.p;
Den = q * B.q;

Rational C(Num, Den);
C.simplifierFraction();
return C;
}

Rational Rational::operator-(Rational B) {
int Num;
int Den;

Num = p * B.q - q * B.p;
Den = q * B.q;

Rational C(Num, Den);
C.simplifierFraction();
return C;
}



Rational Rational::operator*(Rational B)
{
int Num;
int Den;

Num = p * B.p;
Den = q * B.q;

Rational C(Num, Den);
C.simplifierFraction();
return C;
}

Rational Rational::operator/(Rational B)
{
int Num;
int Den;
Rational invB = inverse(B);

Num = p * invB.p;
Den = q * invB.q;

Rational C(Num, Den);
C.simplifierFraction();
return C;
}
...

理性.h

    Rational operator+(Rational B);
Rational operator-(Rational B);
Rational operator*(Rational B);
Rational operator/(Rational B);


private:
int p;
int q;
protected:

测试鼠.cc

int main() {
...
const Rational demi(1,2);
const Rational tiers(1,3);
const Rational quart(1,4);
r0 = demi + tiers - quart;
r1 = 1 + demi;
r2 = 2 - tiers;
r3 = 3 * quart;
r4 = 1 / r0;
...

所以当我尝试运行 TestRat.cc 时,它说:

testrat.cc:31: error: no match for ‘operator+’ in ‘1 + r9’
testrat.cc:52: error: passing ‘const Rational’ as ‘this’ argument of ‘Rational Rational::operator+(Rational)’ discards qualifiers
testrat.cc:53: error: no match for ‘operator+’ in ‘1 + demi’
testrat.cc:54: error: no match for ‘operator-’ in ‘2 - tiers’
testrat.cc:55: error: no match for ‘operator*’ in ‘3 * quart’
testrat.cc:56: error: no match for ‘operator/’ in ‘1 / r0’

为了能够完成这项工作,我必须做什么?谢谢!

最佳答案

tl;博士:

您的运营商应声明为:

Rational operator+(const Rational& B) const;

嗯……至少是这些。 operator = 应该返回对 *this 的引用,但这超出了这个问题的范围。此外,这些运算符被定义为适用于 Rational 对象,而

r1 = 1 + demi; 

尝试对 intRational 对象进行操作。您必须在类之外定义一个适当的运算符:

inline Rational operator+(int, const Rational& r)
{
//...
}

我建议您从 good book 开始学习 C++尽管。只是从这里捡东西,那里并没有真正的工作。

关于c++ - 在 C++ 中扩展运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13616091/

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