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 };
}
相关推荐
小小高不懂写代码5 分钟前
RAG--检索增强生成--原理及实战
前端·人工智能
空中海7 分钟前
04 工程化、质量体系与 React 生态
前端·ubuntu·react.js
无限进步_12 分钟前
二叉搜索树完全解析:从概念到实现与应用场景
c语言·开发语言·数据结构·c++·算法·github·visual studio
努力努力再努力FFF16 分钟前
别再乱学PS、Python了,普通大学生该看懂的技能趋势
开发语言·python
好运的阿财38 分钟前
OpenClaw工具拆解之host_workspace_write+host_workspace_edit
前端·javascript·人工智能·机器学习·ai编程·openclaw·openclaw工具
天若有情6731 小时前
逆向玩家狂喜!用C++野生写法一键破解线性加密(不规范但巨好用)
开发语言·c++·算法
XiYang-DING1 小时前
JavaScript
开发语言·javascript·ecmascript
skywalk81631 小时前
代码高尔夫(Code Golf)是一种以“用最少的字符数实现特定功能”为核心目标的编程挑战或风格。
开发语言
xyq20241 小时前
MySQL 安装配置
开发语言
鸽子一号1 小时前
c#Modbus通信
开发语言·c#