8 非静态数据成员默认初始化

8.1 使用默认初始化

引入

cpp 复制代码
class X {
public:
	X() : a_(0), b_(0.), c_("hello world") {}
	X(int a) : a_(a), b_(0.), c_("hello world") {}
	X(double b) : a_(0), b_(b), c_("hello world") {}
	X(const std::string& c) : a_(0), b_(0.), c_(c) {}
private:
	int a_;
	double b_;
	std::string c_;
};
//这里的代码很冗余 不简洁 

C++11标准提出了新的初始化方法,即在声明非静态数据成员的同时直接对其使用=或者{}

cpp 复制代码
class X {
public:
	X() {}
	X(int a) : a_(a) {}
	X(double b) : b_(b) {}
	X(const std::string& c) : c_(c) {}
private:
	int a_ = 0;
	double b_{ 0. };
	std::string c_{ "hello world" };
}

1.不要使用括号()对非静态数据成员进行初始化,因为这样会造成解析问题,所以会编译错误。

2.不要用auto来声明和初始化非静态数据成员

8.2 位域的默认初始化

cpp 复制代码
/* 定义简单的结构 */
struct
{
  unsigned int widthValidated;
  unsigned int heightValidated;
} status1;
 
/* 定义位域结构 */
struct
{
  unsigned int widthValidated : 1;
  unsigned int heightValidated : 1;
} stat

//默认初始化
struct S {
int y : 8 = 11;
int z : 4 {7};
}

若是存在 条件表达式 

int a;
struct S2 {
int y : true ? 8 : a = 42;
int z : 1 || new int { 0 };
}  这个不存在初始化 它会被看为

int a;
struct S2 {
int y : (true ? 8 : a = 42);
int z : (1 || new int { 0 });
}

正确做法为
int a;
struct S2 {
int y : (true ? 8 : a) = 42;
int z : (1 || new int) { 0 };
}
相关推荐
丈剑走天涯19 分钟前
JDK 17 正式特性
java·开发语言
东方小月23 分钟前
从零开发一个 Coding Agent(四):使用状态机校验大模型事件流
前端·人工智能·后端
秋田君28 分钟前
QT_QFontDialog类字体对话框
开发语言·qt
圣光SG33 分钟前
Java操作题练习(七)
java·开发语言·算法
Csvn42 分钟前
🧩 ESM vs CJS 混用的 7 个「天坑」——从 TypeScript 编译到 Node 与浏览器
前端
Csvn1 小时前
🎯 Web 性能 API 集合:Performance Observer 的 5 个冷门妙用
前端
Csvn1 小时前
深入 React 闭包陷阱:从根源上理解并根治 stale closure
前端
whyfail1 小时前
前端学 Spring Boot(8):接口为什么越用越慢?
前端·spring boot·后端
麻瓜老宋2 小时前
AI开发C语言应用按步走,表达式计算器calc的第二十三步,多行输入、进制输出、错误恢复、常量折叠、配置加载等
c语言·开发语言·atomcode
用户059540174462 小时前
LangChain 记忆测试踩坑实录:这两个坑让我排查了 4 小时
前端·css