c++ - 错误:没有匹配的函数调用'Complex::Complex()'
问题描述
我刚从函数重载开始,我被以下代码困住了:
#include<iostream>
using namespace std;
class Complex
{
double real;
double img;
public:
Complex(double r, double i)
{
real = r;
img = i;
}
void display()
{
cout<<real<<" + i"<<img<<endl;
}
Complex operator+(Complex c)
{
Complex temp;
temp.real = real + c.real;
temp.img = img + c.img;
return temp;
}
Complex operator-(Complex c)
{
Complex temp;
temp.real = real - c.real;
temp.img = img - c.img;
return temp;
}
};
int main()
{
Complex c1(23.89, -42.98), c2(54.23, 53.35);
cout<<"Adding the two complex numbers: "<<endl;
Complex c3 = c1 + c2;
c3.display();
cout<<"Subtracting two complex numbers: "<<endl;
Complex c4 = c1 - c2;
c4.display();
return 0;
}
两个运算符重载函数的错误是:
没有匹配函数调用“Complex::Complex()”复杂温度;^~~~
解决方案
And indeed there is no Complex::Complex()
.
In this code
Complex temp;
temp.real = real + c.real;
temp.img = img + c.img;
return temp;
how do you think temp
is being constructed? The compiler is looking for Complex::Complex()
and when it doesn't find it that's an error.
You could add Complex::Complex()
but the simpler fix is to use the constructor you have already written
Complex temp(real + c.real, img + c.img);
return temp;
Or even simpler, get rid of temp
completely
return Complex(real + c.real, img + c.img);
推荐阅读
- spring-security - X509AuthenticationFilter 方法返回 null
- sql - 使用 Oracle12 中的合并技术在公用表中插入非重复值
- apache-spark - 使用 Spark Operator 在 Kubernetes 中启用多集群故障转移
- android - 无法连接到 Android 调试数据库,即使更改端口
- javascript - react-router-dom 'Link' 不仅适用于代码的一部分,而且在其他地方也能正常工作。有什么问题?
- c - 编写一个程序来检查给定字符串中每个 ASCII 值的相同字符的数量
- vbscript - VBS,从父子结构创建完整的层次结构字符串,递归
- excel - 用于比较两张纸之间的商店名称和发票编号并突出显示匹配的宏
- c++ - 使用 QNetworkReply 请求 POST 超时
- wordpress - ACF:如果用户不是帖子作者,则在 the_loop() 中未正确检索数据