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;
}

运行结果:

相关推荐
大不点wow25 分钟前
Java序列化与反序列化:让对象走出JVM
java·开发语言·jvm
阿里嘎多学长26 分钟前
2026-07-22 GitHub 热点项目精选
开发语言·程序员·github·代码托管
小保CPP28 分钟前
OpenCV C++将多张图像合并为webp动图
c++·人工智能·opencv·计算机视觉
噢,我明白了30 分钟前
Java中日期和字符串的处理
java·开发语言·日期
爱刷碗的苏泓舒30 分钟前
C 语言 if-else 与 switch-case 分支语句对比
c语言·开发语言
-银雾鸢尾-40 分钟前
C#中的泛型约束
开发语言·c#
雪碧透心凉_1 小时前
while 循环与循环嵌套
开发语言·python
乐观勇敢坚强的老彭1 小时前
信奥C++一维数组笔记
开发语言·c++·笔记
码上有光1 小时前
异常和智能指针
java·大数据·c++·servlet·异常·智能指针
这就是佬们吗1 小时前
Python入门⑤-异常处理、文件操作与实战项目
开发语言·数据库·python·算法·pycharm