0
点赞
收藏
分享

微信扫一扫

c++初始化方式

对类型进行初始化时,语法是相当的多,为什么要这么多初始化方法呢?主要是以前各种类型的初始化方式不同,现在演变成如此多的方式就是为了使初始化常规变量的方式与初始化类变量的方式更像。大括号初始化器是后来扩展出的用于任何类型,所以尽量使用大括号初始化语法。

1、基本类型初始化

int math = 12;
int math(12);
int math{12};
int math = {12};
int year = math;//可以使用一个变量初始化另一个变量。

2、数组类型初始化

int maths[2] = {};//默认0
int maths[2] = {10,20};
int maths[2]{10,20};
int year[] = maths; //不行,不能使用数组初始化另一个数组

3、字符串

char name[11] = "helloworld";//需要注意的是字符串数组最后有个\0
char name[]{"helloworld"};
string names = {"helloworld"};
string names{"helloworld"};
string str2 = names; //可以使用字符串初始化另一个字符串

4、结构体

struct scrle {
	char name[10];
	int len;
};

scrle abc = {
	"aaa",
	10
};

scrle abc {
	"aaa",
	10
};


举报

相关推荐

c++ 初始化

C++——初始化列表

C++ | 类对象初始化

C++成员初始化列表

C++ —— 常见的初始化

0 条评论