c++ - 为什么按值发送参数时默认复制构造函数不调用?
问题描述
该程序初始化一个类的对象并将其作为参数传递给另一个成员函数。当我发表声明时
Address a2=a1;
它没有显示错误。但是当我将参数作为对象时
Employee(int id, string name, Address address);
并使用它调用它
Employee e1 = Employee(101,"Nakul",a2);
它显示以下错误。
#include <iostream>
using namespace std;
class Address {
public:
string addressLine, city, state;
Address(string addressLine, string city, string state)
{
this->addressLine = addressLine;
this->city = city;
this->state = state;
}
};
class Employee
{
private:
Address address; //Employee HAS-A Address
public:
int id;
string name;
Employee(int id, string name, Address address) //Here it is showing an error
{
this->id = id;
this->name = name;
this->address = address;
}
void display()
{
cout<<id <<" "<<name<< " "<<
address.addressLine<< " "<< address.city<< " "<<address.state<<endl;
}
};
int main(void) {
Address a1= Address("C-146, Sec-15","Noida","UP");
Address a2=a1; //Here it is showing no error.
Employee e1 = Employee(101,"Nakul",a2);
e1.display();
return 0;
}
错误是
error: no matching function for call to ‘Address::Address()’
{
^
解决方案
在 的构造函数中Employee
,address
成员初始化列表中没有提到该成员。然后它会首先被默认初始化,然后this->address = address;
在Employee
. 但Address
没有默认构造函数。
您可以在成员初始化器列表中将其初始化为
Employee(int id, string name, Address address) : address(address)
// copy-initialize (via copy constructor)
{
this->id = id;
this->name = name;
}
然后address
通过复制构造函数从构造函数参数复制初始化。
推荐阅读
- sharepoint-online - CSOM 在大型库中按文件名过滤
- reactjs - 如何从无限重新渲染中离开?
- python - 根据分组数据框中列的前两个值的差异获取子数据框
- javascript - 如何单击按钮切换滑块的图像
- python - Python3 __init__.py 如何存储包信息?
- java - Android Java Play gif 只播放一次
- c++builder - 更改线序时,网格内 FDQuery 的 Refresh() 函数似乎不起作用
- excel - Excel VBA 宏 - 类范围的复制方法失败
- c# - 是否可以在不加载 EF6 的情况下修改实体上的导航集合?
- javascript - Quill.js 和段落