【发布时间】:2020-12-29 06:40:35
【问题描述】:
我声明一个类 comp 用于添加复数,在 add() 函数中声明第三个 comp 对象时弹出错误 错误:没有匹配函数调用'comp::comp()'
下面给出的代码绝对可以正常工作
class comp
{
float real;
float img;
public:
comp()
{
real=img=0;
}
comp(float a,float b)
{
real=a;
img=b;
}
void display()
{
cout<<real<<"+"<<img<<"i"<<endl;
}
friend comp add(comp, comp);
};
在代码中,我已经注释了默认构造函数 这会产生错误
class comp
{
float real;
float img;
public:
/*comp()
{
real=img=0;
}*/
comp(float a,float b)
{
real=a;
img=b;
}
void display()
{
cout<<real<<"+"<<img<<"i"<<endl;
}
friend comp add(comp, comp);
};
在下面的代码中,我已经在参数化构造函数中初始化了参数 这也很好用
class comp
{
float real;
float img;
public:
comp(float a=0,float b=0)
{
real=a;
img=b;
}
void display()
{
cout<<real<<"+"<<img<<"i"<<endl;
}
friend comp add(comp, comp);
};
我在下面粘贴 add() 函数的代码
comp add(comp c1, comp c2)
{
comp c3; //*The error pops up at this declaration*
c3.real=c1.real+c2.real;
c3.img=c1.img+c2.img;
return c3;
}
【问题讨论】:
-
您似乎找到了答案。
comp c3;仅在存在可以不带参数调用的构造函数时才有效。 -
对。你写了
comp c3;。这将调用不带参数的构造函数。但是没有没有参数的构造函数。所以它向你抱怨并说没有没有参数的构造函数。
标签: c++ oop parameters constructor default-constructor