C++——初始化列表的使用

1.初始化列表的格式

Test() :ci(10) { }

复制代码
#include <stdio.h>
class Test {
private:
	const int ci;
public:
	Test() :ci(10) {

	}
	int getCI() {
		return ci;
	}
};

int main() {
	Test t;
	printf("t.ci=%d\n", t.getCI()); //10
	return 0;
}

2.注意事项:

(1)成员的初始化顺序与成员的声明顺序相同

(2)成员的初始化顺序与初始化列表中的位置无关

(3)初始化列表先于构造函数的函数体执行

复制代码
#include <stdio.h>
class Value {
private:
	int mi = 0;//不能在这边进行初始化,只能使用初始化列表
public:
	Value(int i) {
		printf("i=%d\n", i);
		mi = i;
	}
	int getI() {
		return mi;
	}
};
class Test {
private:
	//Value m2(1);报错,因为编译器会误解为 "函数声明",在main函数中可以用这种初始化方法
	Value m2;
	Value m3;
	Value m1;
public:
	Test():m1(1),m2(2),m3(3){
		printf("Test::Test()\n");
	}

};
int main() {
	Test t; //i=2,i=3,i=1 Test::Test()
	return 0;
}

3.类中的const成员

(1)类中的const成员会被分配空间,如果当前对象在栈上分配空间,则cons成员也在栈上,如果在堆中分配空间,则const成员也在堆上

(2)类中的const成员的本质是只读变量

(3)类中的const成员只能在初始化列表中指定初始值

复制代码
#include <stdio.h>
class Value {
private:
	int mi = 0;//不能在这边进行初始化,只能使用初始化列表
public:
	Value(int i) {
		printf("i=%d\n", i);
		mi = i;
	}
	int getI() {
		return mi;
	}
};
class Test {
private:
	//Value m2(1);报错,因为编译器会误解为 "函数声明",在main函数中可以用这种初始化方法
	const int ci;
	Value m2;
	Value m3;
	Value m1;
public:
	Test():m1(1),m2(2),m3(3),ci(100){
		printf("Test::Test()\n");
	}
	int getCI() {
		return ci;
	}
	void setCI(int v) {
		int* p = const_cast<int*>(&ci);
		*p = v;
	}
};
int main() {
	Test t; 
	printf("t.ci=%d\n", t.getCI());
	t.setCI(10);
	printf("t.ci=%d\n", t.getCI());
	return 0;
}

运行结果:

相关推荐
saltymilk16 小时前
使用 C++ 模拟 ShaderLanguage 的 swizzle
c++·模板元编程
xlp666hub1 天前
Leetcode第五题:用C++解决盛最多水的容器问题
linux·c++·leetcode
得物技术1 天前
搜索 C++ 引擎回归能力建设:从自测到工程化准出|得物技术
c++·后端·测试
xlp666hub2 天前
Leetcode 第三题:用C++解决最长连续序列
c++·leetcode
会员源码网2 天前
构造函数抛出异常:C++对象部分初始化的陷阱与应对策略
c++
xlp666hub2 天前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
不想写代码的星星2 天前
static 关键字:从 C 到 C++,一篇文章彻底搞懂它的“七十二变”
c++
xlp666hub3 天前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
不想写代码的星星3 天前
C++继承、组合、聚合:选错了是屎山,选对了是神器
c++
不想写代码的星星4 天前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++