类中对象的初始化

问题描述 投票:0回答:1
class CustomerId{
    public:
        CustomerId(int a) : a_(a){
            std::cout << a;
        }
        
    private:
        int a_{0};
};

class Customer {

  public:
    Customer(int a): customer_id_(a){}

  private:
   CustomerId customer_id_;
};

如果这非常愚蠢,我很抱歉,但我一直致力于理解在其他 B 类中声明的 A 类对象是如何工作的。

在这个例子中,我们将

CustomerId customer_id_
声明为类
Customer
中的成员变量。我的假设是我需要为
CustomerId
创建一个默认构造函数,因为声明也会创建一个对象。我从如何在声明时初始化基元(例如
a_{0}
中的
CustomerId
)中获取线索。

但看起来并非如此。

有人可以帮助我理解在其他类中声明为成员变量的对象是如何工作的吗? 谢谢你

c++ oop c++11
1个回答
0
投票

我的假设是我需要为 CustomerId 创建一个默认构造函数,因为声明也会创建一个对象。

并非如此 – 类的声明不会创建该类的对象 – 当您声明该类的对象(或以其他方式创建一个)时,构造函数就是这样做的。

在您的情况下,

Customeronly

 构造函数通过 
CustomerId
 调用正确初始化初始化程序列表中的 
customer_id_(a)
 成员。把它去掉,或者为 
Customer
 添加一个默认构造函数,你会得到一个错误。例如:

class CustomerId { public: CustomerId(int a) : a_(a) { std::cout << a; } private: int a_{ 0 }; }; class Customer { public: Customer() {}; // Error: 'CustomerId': no appropriate default constructor available Customer(int a) : customer_id_(a) {} private: CustomerId customer_id_; };
在您显示的代码中, 

Customer

 的默认构造函数被隐式删除(因为您已经定义了另一个),因此如果没有对 ( 的适当调用,则无法创建 
Customer
 对象嵌入 
CustomerId
 对象的非默认)构造函数。

© www.soinside.com 2019 - 2024. All rights reserved.