因此,我在一本书中找到了以下代码:
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()”为什么?我该怎么做?
发布于 2018-06-16 17:17:35
您定义了自己的构造函数,因此默认构造函数定义为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;
}
};我将创建非成员operator+,而不是创建sum成员函数
// 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;https://stackoverflow.com/questions/50886531
复制相似问题