C++类成员变量与构造函数谁先初始化

C++类成员变量与构造函数谁先初始化,第1张

C++类成员变量与构造函数谁先初始化 先来看例子,求输出结果
#include 
using namespace std;

class derived
{
public:
  derived() { cout << "derived::derived()" << endl; }
};

class derived1
{
public:
  derived1() { cout << "derived1::derived1()" << endl; }
  ~derived1() { cout << "derived1::~derived1()" << endl; }
};

class base2
{
  derived1 d1;
public:
  // derived1 d1;
  base2() { cout << "base2::base2()" << endl; }
  ~base2() { cout << "base2::~base2()" << endl; }
};

int main()
{
  base2 b2;

  return 0;
}
看实际输出

图片可能不可见,输出如下:

derived1::derived1()
base2::base2()
base2::~base2()
derived1::~derived1()
总结 C++的成员变量先于构造函数执行前被分配内存并执行该变量内部的构造函数(如果需要的话)

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/3002061.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-09-27
下一篇 2022-09-27

发表评论

登录后才能评论

评论列表(0条)

保存