首页 > 解决方案 > 为什么按值发送参数时默认复制构造函数不调用?

问题描述

该程序初始化一个类的对象并将其作为参数传递给另一个成员函数。当我发表声明时

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()’
        {
        ^

标签: c++oopconstructor

解决方案


在 的构造函数中Employeeaddress成员初始化列表中没有提到该成员。然后它会首先被默认初始化,然后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通过复制构造函数从构造函数参数复制初始化。


推荐阅读