构造函数初始化列表
- 推荐在构造函数初始化列表中进行初始化
- 构造函数的执行分为两个阶段
- 初始化段
- 普通计算段(函数体内的代码块)
对象成员及其初始化
#include <iostream>
using namespace std;
class Object
{
public:
Object(int num) : num_(num)
{
cout<<"Object ...."<<num_<<endl;
}
~Object()
{
cout<<"~Object ...."<<endl;
}
private:
int num_;
}
class Container
{
public:
Container(int obj1=0,int obj2=0) : obj1_(obj1),obj2_(obj2)
{
cout<<"Container...."<<endl;
}
~Container()
{
cout<<"~Container...."<<endl;
}
private:
Object obj1_;
Object obj2_;
}
int main()
{
Container c(10,20);
return 0;
}
const成员、引用成员初始化
#include <iostream>
using namespace std;
class Object
{
public:
Object(int num=0) : num_(num),kNum_(num),refNum_(num_)
{
cout<<"Object ...."<<num_<<endl;
}
~Object()
{
cout<<"~Object ...."<<endl;
}
private:
int num_;
const int kNum_;
int& refNum_;
}
int main()
{
Object obj(10);
return 0;
}