在C++类中经常遇到初始化的问题,如果在构造函数中初初始化一些数据,那就得注意构造函数的调用顺序了
以下示例证明成员变量的构造函数是先执行的:
//console.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class A{
public:
A()
{
cout<<"A构造\r\n";
}
};
class B{
public:
B()
{
cout<<"B构造\r\n";
}
A m_A;
void Print(void)
{
cout<<"Hello";
}
};
int _tmain(int argc, _TCHAR* argv[])
{
B b;
b.Print();
return 0;
}
输出结果如下:
A构造
B构造
Hello