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

运行结果:

相关推荐
卷无止境2 小时前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
卷无止境3 小时前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
郝学胜_神的一滴1 天前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
卷无止境3 天前
C++ 的Eigen 库全解析
c++
卷无止境3 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴3 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake
博客18005 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴5 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
众少成多积小致巨6 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
clint45610 天前
C++进阶(1)——前景提要
c++