初始化列表完成数据成员赋值比构造函数内部赋值更高,而且有些数据类型必须在初始化列表中进行初始化如const数据成员,引用数据成员,没有默认构造函数的对象数组成员,没有默认构造函数的超类
使用示例:
#include <iostream>
#include <string>
using namespace std;
class test
{
private :
int mOne;
double mTwo;
string mstr;
const string kstr;
public :
//没有形参的初始化列表
test():mstr("this a string"){
}
//带一个形参的初始化列表
test(const string str):kstr("the is const"){
}
//为const 变量赋值是不可以的
//test(const string str){
// this->kstr=str;
//}
//带有两个形参的初始化列表
//变量值与声明顺序一样
test(int mOne,double mTwo):mTwo(2),mOne(1){
}
void getOne(){
cout<<"one: "<<this->mOne<<endl;
}
void getTwo(){
cout<<"two: "<<this->mTwo<<endl;
}
void getStr(){
cout<<"mstr: "<<this->mstr<<endl;
}
void getCon(){
cout<<"kstr: "<<this->kstr<<endl;
}
};
int main(){
test one(1,2);
one.getOne();
one.getTwo();
test thr;
thr.getStr();
test con("12");
con.getCon();
return 0;
}
结果: