我定义了一个Fraction类,如下所示,重载了“=”&“+”运算符。
我使该程序尽可能简单以显示问题。
#include <iostream>
class Fraction {
private:
int nominator;
int denominator;
public:
Fraction ();
Fraction (int, int);
Fraction & operator = (Fraction &);
friend Fraction operator + (Fraction &, Fraction &);
// static function:
// find the Greatest Common Divisor of two numbers
int static GCD(int x, int y);
};
int Fraction::GCD(int x, int y) {
if (y == 0) {
return x;
} else {
return GCD (y, x % y);
}
}
Fraction::Fraction () {
nominator = NULL;
denominator = NULL;
}
Fraction::Fraction (int num_1, int num_2) {
int divisor = Fraction::GCD (num_1, num_2);
nominator = num_1 / divisor;
denominator = num_2 / divisor;
}
Fraction & Fraction::operator = (Fraction &A) {
nominator = A.nominator;
denominator = A.denominator;
return *this;
}
Fraction operator + (Fraction &A, Fraction &B) {
int nominator = A.nominator * B.denominator + B.nominator * A.denominator;
int denominator = A.denominator * B.denominator;
int divisor = Fraction::GCD (nominator, denominator);
return Fraction (nominator / divisor, denominator / divisor);
}
在Main()函数中,我有三个测试用例
int main(int argc, const char * argv[]) {
Fraction frac_a = Fraction(1, 3);
Fraction frac_b = Fraction(1, 4);
// test 1: no compile error
frac_a + frac_b;
frac_a = frac_b;
// test 2: no compile error
Fraction frac_c = frac_a + frac_b;
// test 3: Error: No viable overloaded '='
Fraction frac_d;
frac_d = frac_a + frac_b;
return 0;
}
问题是,为什么“测试3”有“没有可行的过载'='”错误?
最佳答案
您将赋值operator=
定义为将左值引用作为参数,但尝试将其临时传递。临时对象仅绑定(bind)到 const 引用或右值引用。
您应该阅读如何以可用的方式重载运算符,例如operator+
接受的非常量左值引用也会发生相同的问题。
也就是说,使用Fraction& operator=(Fraction const&)
和Fraction operator+(Fraction const&, Fraction const&)
。
关于c++ - C++中的运算符重载失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34200181/