c ++初始化列表

0 c++ initialization

我有一个关于c ++初始化列表的问题,我在下面看到以下代码:

class A {
public:
  A(String sender, String receiver, String service) {
                                                        //do something here
                                                    }
}

class B {
public:
  B(String sender, String receiver, String service) {
                                                        //do something here
                                                    }
}
Run Code Online (Sandbox Code Playgroud)

然后以下列方式创建对象:

A::A(sender,receiver, service) : B(sender,receiver, service) {
//do something here
}
Run Code Online (Sandbox Code Playgroud)

B也将根据通过的参数创建吗?怎么会发生这种情况?

Luc*_*ore 5

您发布的代码是错误的.

首先,要调用这样B的构造函数,A必须从中派生出来B.

其次,您提供了2个实现A::A.

我将在下面的例子中解释:

class B
{
   int _x;
public:
   B();
   B(int x);
}

B::B()
{
   _x = 42;
}
B::B(int x)
{
   _x = x;
}

class A : public B
{
public:
    A(int x);
};

A::A(int x) : B(x) {}
Run Code Online (Sandbox Code Playgroud)

现在,因为Ais-a B(这就是继承是什么),每当你构造A一个基础对象时 - B也将被构造.如果未在初始化列表中指定它,则将调用B- 的默认构造函数B::B().即使您没有声明,它确实存在.

如果指定构造函数的不同版本(如本例所示),B::B(int)则将调用该版本.

这就是语言设计的方式.

编辑:

我编辑了一下代码.

假设A构造函数的以下定义:

A::A(int x) : B(x) {}
//...
A a(10);
//a._x will be 10
Run Code Online (Sandbox Code Playgroud)

但是,如果您的构造函数定义为:

A::A(int x) {}
Run Code Online (Sandbox Code Playgroud)

B将调用默认构造函数:

A a(10);
//a._x will be 42
Run Code Online (Sandbox Code Playgroud)

希望很清楚.