标签:error ima span log ror ios 构造函数 std pac
1、构造函数初始化列表
推荐在构造函数初始化列表中进行初始化
构造函数的执行分为两个阶段:初始化段、 普通计算段
2、对象成员及其初始化
1 #include<iostream> 2 using namespace std; 3 4 class Object 5 { 6 public: 7 Object(int num) :num_(num) 8 { 9 cout << "Object..." <<num_<<"..."<< endl; 10 } 11 ~Object() 12 { 13 cout << "~Object..." << num_ << "..." << endl; 14 } 15 private: 16 int num_; 17 }; 18 class Container 19 { 20 public: 21 Container(int obj1=0, int obj2=0):obj1_(obj1), obj2_(obj2) 22 { 23 cout << "Container..." << endl; 24 } 25 ~Container() 26 { 27 cout << "~Container..." << endl; 28 } 29 private: 30 Object obj1_; 31 Object obj2_; 32 }; 33 int main(void) 34 { 35 Container c(10,20);//先构造Object,再是Container析构次序相反 36 37 return 0; 38 }
3、const成员、引用成员的初始化
const成员的初始化只能在初始化列表中进行
1 #include<iostream> 2 using namespace std; 3 4 //对象成员(对象所对应的类没有默认构造函数)的初始化,只能在构造函数初始化列表中进行 5 class Object 6 { 7 public: 8 Object(int num=0) :num_(num), kNum_(num), redNum_(num_) 9 { 10 //kNum_=100; ERROR 11 //redNum_ = num; ERROR 12 cout << "Object..." << num_ << "..." << endl; 13 } 14 ~Object() 15 { 16 cout << "~Object..." << num_ << "..." << endl; 17 } 18 private: 19 int num_; 20 const int kNum_; //const成员的初始化只能在构造函数初始化列表中进行 21 int& redNum_; //引用成员的初始化只能在构造函数初始化列表中进行 22 }; 23 24 int main(void) 25 { 26 Object obj(10); 27 28 return 0; 29 }
加入枚举类型
#include<iostream> using namespace std; class Object { public: enum E_TYPE { TYPE_A=100, TYPE_B=200 }; public: Object(int num=0) :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(10); Object obj2(20); obj1.DisplaykNum_(); obj2.DisplaykNum_(); cout << obj1.TYPE_A << endl; cout << obj2.TYPE_A << endl; cout << Object::TYPE_A << endl; return 0; }
标签:error ima span log ror ios 构造函数 std pac
原文地址:http://www.cnblogs.com/xiaotongtt/p/6128024.html