c++ - 为什么我们需要在参数化构造函数中预先初始化参数?
问题描述
我声明一个类 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);
};
在代码中,我已经注释了 Default 构造函数,这会产生一个错误
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;
}
解决方案
您不是在“初始化参数”,而是在声明一个具有参数默认值的函数。这使得可以在不显式传递任何内容的情况下调用函数,因此它可以不带参数调用。
推荐阅读
- amazon-web-services - 如何部署具有多个角色的 Terraform 模块?
- angular - 如何始终将焦点设置在 Angular 中的输入上
- reinforced-typings - 如何在 Reinforced.Typings 中将属性标记为可为空(“type | null”)?
- javascript - 单击鼠标滚轮后删除 :focus 及其样式
- c# - 用这个访问 c# 中的单例类;
- swiftui - 如何在 SwiftUI 中屏蔽/剪辑图像的底部?
- python - 如何有效地对子数组进行操作,例如计算行列式,逆,
- html - 是否可以包装一个
- reactjs - 我使用 React 和 PHP 制作的联系表返回 mailSent: false
- mariadb - 我可以在集群上使用主从复制吗?