初始化列表---类和对象 c++

初始化列表---类和对象 c++,第1张

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录
  • 前言
  • 二、使用步骤
    • 1.传统的初始化(创建对象的时候赋初值)
    • 2.初始化列表时初始化属性


前言

语法:构造函数():类型(参数),类型(参数)…


二、使用步骤 1.传统的初始化(创建对象的时候赋初值)

代码如下(示例):

#include
using namespace std;
class person{
	public:
		//常用的初始化 
		person(int a,int b,int c)
		{
			A=a;
			B=b;
			C=c;
		}
		int A;
		int B;
		int C; 
};
void test()
{
	person p(10,10,20);
	cout<<"A="<<p.A<<endl;
	cout<<"B="<<p.B<<endl;
	cout<<"C="<<p.C<<endl;
}
int main(){
	test();
	return 0;
}
2.初始化列表时初始化属性

代码如下(示例):

#include
using namespace std;
class person{
	public:
```	person():A(10),B(20),C(20) 
		{
			
		}
		int A;
		int B;
		int C; 
};

 
void test()
{
	person(int a,int b,int c):A(a),B(b),C(c)//有没有感觉更麻烦了哈哈哈 
		{
			
		}
		int A;
		int B;
		int C; 
};

 
void test()
{
	person p(102030;
	cout<<"A="<<p.A<<endl;
	cout<<"B="<<p.B<<endl;
	cout<<"C="<<p.C<<endl;
}
int main(){
	test();
	return 0;
}

使用初始化列表少了一次调用默认构造函数的过程,这对于数据密集型的类来说,是非常高效的。虽然写起来麻烦了,又臭又长哈哈哈

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/789563.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-05
下一篇2022-05-05

发表评论

登录后才能评论

评论列表(0条)

    保存