文章目录提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
- 前言
- 二、使用步骤
- 1.传统的初始化(创建对象的时候赋初值)
- 2.初始化列表时初始化属性
前言
语法:构造函数():类型(参数),类型(参数)…
二、使用步骤 1.传统的初始化(创建对象的时候赋初值)
代码如下(示例):
#include2.初始化列表时初始化属性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="< test(); return 0; }
代码如下(示例):
#includeusing 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(10,20,30); cout<<"A="< test(); return 0; }
使用初始化列表少了一次调用默认构造函数的过程,这对于数据密集型的类来说,是非常高效的。虽然写起来麻烦了,又臭又长哈哈哈



