Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

C++初始化列表探索

$
0
0

初始化列表完成数据成员赋值比构造函数内部赋值更高,而且有些数据类型必须在初始化列表中进行初始化如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;
}

结果:


作者:buyingfei888 发表于2013-11-17 16:39:29 原文链接
阅读:36 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>