所以,我在一本书中找到了这个代码:
class complex
{
public:
float x,y;
complex(float a, float b) // CONSTRUCTOR
{
x=a; y=b;
}
complex sum (complex z)
{
***complex c;*** // i get the error here
c.x=x+z.x;
c.y=y+z.y;
return c;
}
};
这段代码可以帮助我总结2个复数,如:
int main ()
{
complex a(1,2),b(1,1),c; // first number in paranthesis is the real part, the
// second one is the imaginary part
c=a.sum(b) ; // c should get the value of a+b (c.x=2, c.y=3)
return 0;
}
但每次我尝试编译它时都会收到此错误: “没有用于调用complex :: complex()的匹配函数” 为什么?我该怎么办?
答案 0 :(得分:1)
您定义了自己的构造函数,因此默认构造函数定义为complex() = delete;
。您需要自己的构造函数或强制创建默认构造函数
class complex
{
public:
float x = 0;
float y = 0;
complex() = default; // Compiler will generate the default constructor
complex(float a, float b): x(a), y(b) {}
complex sum (complex z)
{
complex c;
c.x=x+z.x;
c.y=y+z.y;
return c;
}
};
我会创建非成员sum
operator+
成员函数
// No need to make it friend because you declared x and y as public
complex operator+(complex const& a, complex const& b) {
return complex(a.x + b.x, a.y + b.y);
}
并像这样使用
complex a(3, 4), b(5, 6);
complex c = a + b;