初始化列表
#include<iostream>
#include<string>
using namespace std;
//初始化列表
//在c++的使用过程当中,常常需要在构造函数当中对类的成员变量进行初始化,通常的方法有两种
//第一种初始化的方式:在构造函数体内通过赋值语句初始化
//Thing(int a, int b, int c){ x = 1; y = b; z = c }
//第二种方法:使用初始化列表形式初始化
//Thing(int a, int b, int c) :x(a), x(b), z(c){}
//程序中为什么要使用初始化列表?
/*
*1、对于类类型的成员,使用初始化列表效率更高
*2、有些类型的成员变量必须使用初始化列表的形式初始化,如const成员 引用成员
*3、在继承时,子类的构造函数中初始化父类的成员时
*
*/
//class Thing
//{
//public:
// //Thing(int a){ x = a; } //当x时被const修饰的时候,这样写x不能被a赋值
//
// Thing(int a) :x(a){}//使用初始化列表形式初始化 就可以为被const修饰的x值赋值
//
// Thing(int b) :y(b){}
//private:
// const int x;
// int& x;
//};
//
//int main()
//{
// Thing t(1);
// return 0;
//}
//练习:初始化列表的使用
class Thing
{
public:
Thing(int _x, int _y) :x(_x), y(_y){}
void print()
{
cout << "x=" << x << ",y=" << y << endl;
}
private:
int x;
int y;
};
int main(int argc, const char * argv[])
{
Thing t(1, 1);
t.print();
return 0;
}