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 };
}
相关推荐
竹林81813 分钟前
用 The Graph 查询链上数据实战:从手搓 RPC 到 Subgraph,我的 NFT 项目数据加载快了 10 倍
前端·javascript
妙码生花29 分钟前
从 PHP 到 AI + Golang,程序员自救转型手记(十九):点选验证码代码逐行目检
前端·后端·go
Awu12271 小时前
⚡从零开发 Agent CLI(五)实现一个可治理、可扩展的工具系统
前端·人工智能·claude
咪库咪库咪2 小时前
Vue3-生命周期
前端
莪_幻尘2 小时前
你的 AI Skill 越多越蠢?Token 上下文爆炸的求生指南
前端·ai编程
lichenyang4532 小时前
从 has.echo 到异步 API 注册表:一次 ASCF API 回调不触发的排查复盘
前端
林瞅瞅3 小时前
Nuxt3 项目部署 Nginx 防盗链后特定 JS 文件 403 问题修复方案
前端
kyriewen3 小时前
别再每次都 Google 了:我整理了前端日常最常踩的 10 个 Git 坑,附速查表
前端·javascript·git
一颗奇趣蛋3 小时前
Web 视频开发完全指南:从入门到精通
前端
非洲农业不发达4 小时前
windows终端体验大升级,让你拥有macos级别的美化
前端·后端