C++ 为什么我会出错:没有可行的重载'=';
所以我试着让它运行,但我一直在运行C++ 为什么我会出错:没有可行的重载'=';,c++,C++,所以我试着让它运行,但我一直在运行 result = f1.AddedTo(f2); //a class binary operation - a value-returning "observer" function ~~~~~~ ^ ~~~~~~~~~~~~~~ note: candidate function (the implicit copy assignment operator) not viable: no known conversion from 'int' to 'cons
result = f1.AddedTo(f2); //a class binary operation - a value-returning "observer" function
~~~~~~ ^ ~~~~~~~~~~~~~~
note: candidate function (the implicit copy assignment operator) not viable: no known conversion from 'int' to 'const fraction' for 1st argument
class fraction
^
代码:
//client.cpp
#包括
#包括“分数.h”
使用名称空间std;
int main()
{
分数f1(9,8);//调用参数化类构造函数
分数f2(2,3);
分数结果;//调用默认类构造函数
常数分数f3(12,8);
常数分数f4(202303);
分数f5,f6;
你可以有一个分数类和两个分数s:result
和f1
。你在f1
上调用fraction::AddedTo
,并尝试分配结果(一个int
)到结果
;但是,编译器不知道如何将单个int
分配给分数
为此,您需要为您的分数:
fraction& operator=(int n)
{
numerator = denominator = n; // or however you wish to handle this
return *this;
}
默认情况下,编译器可以将两个分数
相加,因为它只是猜测您希望执行以下操作:
fraction& operator=(const fraction& f)
{
numerator = f.numerator;
denominator = f.denominator;
return *this;
}
但是对于其他的事情,你需要重载操作符。为什么?一旦我阅读了你的400多行代码,我会告诉你。你可以通过提供一个。作为暗中操作:因为你的分数类没有重载的操作符=
,所以编译器不知道你希望如何添加分数
和一个int
(由AddedTo
返回)一起。您需要定义一个自定义的操作符=
为什么要AddedTo
,Subtract
等。所有的返回类型都是int
,但是返回分数(…);
?什么是分数
?您的类型是分数
。
fraction& operator=(const fraction& f)
{
numerator = f.numerator;
denominator = f.denominator;
return *this;
}