C++笔记----构造函数与析构函数(三)

1、构造函数初始化列表

推荐在构造函数初始化列表中进行初始化

构造函数的执行分为两个阶段:初始化段、 普通计算段

2、对象成员及其初始化

 #include<iostream>
using namespace std; class Object
{
public:
Object(int num) :num_(num)
{
cout << "Object..." <<num_<<"..."<< endl;
}
~Object()
{
cout << "~Object..." << num_ << "..." << endl;
}
private:
int num_;
};
class Container
{
public:
Container(int obj1=, int obj2=):obj1_(obj1), obj2_(obj2)
{
cout << "Container..." << endl;
}
~Container()
{
cout << "~Container..." << endl;
}
private:
Object obj1_;
Object obj2_;
};
int main(void)
{
Container c(,);//先构造Object,再是Container析构次序相反 return ;
}

C++笔记----构造函数与析构函数(三)

3、const成员、引用成员的初始化

const成员的初始化只能在初始化列表中进行

 #include<iostream>
using namespace std; //对象成员(对象所对应的类没有默认构造函数)的初始化,只能在构造函数初始化列表中进行
class Object
{
public:
Object(int num=) :num_(num), kNum_(num), redNum_(num_)
{
//kNum_=100; ERROR
//redNum_ = num; ERROR
cout << "Object..." << num_ << "..." << endl;
}
~Object()
{
cout << "~Object..." << num_ << "..." << endl;
}
private:
int num_;
const int kNum_; //const成员的初始化只能在构造函数初始化列表中进行
int& redNum_; //引用成员的初始化只能在构造函数初始化列表中进行
}; int main(void)
{
Object obj(); return ;
}

加入枚举类型

#include<iostream>
using namespace std; class Object
{
public:
enum E_TYPE
{
TYPE_A=,
TYPE_B=
};
public:
Object(int num=) :num_(num), kNum_(num), redNum_(num_)
{
cout << "Object..." << num_ << "..." << endl;
}
~Object()
{
cout << "~Object..." << num_ << "..." << endl;
}
void DisplaykNum_()
{
cout << "kNum_" << kNum_ << endl;
}
private:
int num_;
const int kNum_;
int& redNum_;
}; int main(void)
{
Object obj1();
Object obj2();
obj1.DisplaykNum_();
obj2.DisplaykNum_();
cout << obj1.TYPE_A << endl;
cout << obj2.TYPE_A << endl;
cout << Object::TYPE_A << endl;
return ;
}

C++笔记----构造函数与析构函数(三)

上一篇:web & Rich Text Editor


下一篇:Angularjs2 入门