繁体   English   中英

C++类对象初始化

[英]C++ class object initialization

我是 C++ 新手,想知道如何调用 A 类构造函数,因为 B 的默认构造函数没有初始化 A。 注意:B 类不是从 A 类继承的

#include "iostream"
using namespace std;
class A
{
    public:
    A() { cout << "A's Constructor Called " << endl;  }
};

class B
{
    A a;
    public:
    B() { cout << "B's Constructor Called " << endl; }
};

int main()
{
    B b1;
    return 0;
}

Output is :
A's Constructor Called
B's Constructor Called

因为您没有告诉 B 如何构造其数据成员a ,它将使用 A 的默认构造函数。 如果 A ddn 没有默认构造函数,则会出现编译器错误。 呼吁非默认构造a从B的构造方法,请参见下面的代码:

#include "iostream"
using namespace std;
class A
{
    public:
    A() { cout << "A's Constructor Called " << endl;  }
    A(int) {  cout << "A's int Constructor Called " << endl;  }
};

class B
{
    A a;
    public:
    B() { cout << "B's Constructor Called " << endl; }
    B(int i) : a(i) { cout << "B's int Constructor Called " << endl; }
};

int main()
{
    B b1;
    B b1(1); // this would call the two new constructors
    return 0;
}

类 B 的构造函数初始化类的所有成员,特别是A a 由于类 A 有一个构造函数,因此在运行构造函数中的代码之前实例化类 B 时会调用它。 这意味着构造函数中的代码可以访问 B 的所有初始化成员。因此,正如您所观察到的,B 类对象的构造首先调用 A 类对象 a 的构造,然后给出关于 B 的输出构造函数。

我正在寻找类似下面的东西,终于能够弄清楚了。

用于设置对象初始状态的构造函数。 在继承层次结构的情况下,基类对象将按照继承层次结构(OO 术语中的 IS-A 关系)的顺序构造,然后是派生类对象。

类似地,当一个对象嵌入到另一个对象中时(OO 术语中的 HAS-A 关系或包含),嵌入对象的构造函数按其声明的顺序被调用。

在上述情况下,A 嵌入在 B 中。在构造 'b1' 对象之前,A 的构造函数被调用以设置状态 'a'。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM