Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/147.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么我会出错:没有可行的重载'=';_C++ - Fatal编程技术网

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;
}