Why can in-class initializers only use = or {}?(为什么类内初始化器只能使用 = 或 {}?)
问题描述
类内初始化器(C++11 特性)必须用 curl 括起来大括号或跟随一个 = 符号.它们不能在括号内指定.
In-class initializers (C++11 feature) must be enclosed in curly braces or follow a = sign. They may not be specified inside parenthesis.
这是什么原因?
推荐答案
我对此并不是 100% 肯定,但这可能是为了防止语法歧义.例如,考虑以下类:
I am not 100% positive about this, but this might be to prevent a syntax ambiguity. For example, consider the following class:
class BadTimes {
struct Overloaded;
int Overloaded; // Legal, but a very strange idea.
int confusing(Overloaded); // <-- This line
};
指示的行是什么意思?正如所写,这是一个名为 confusing 的成员函数的声明,它接受一个 Overloaded 类型的对象作为参数(其名称未在函数声明中指定)和返回一个 int.如果 C++11 允许初始化器使用括号,这将是模棱两可的,因为它也可能是一个名为 confusing 的 int 类型成员的定义,该成员被初始化到数据成员 Overloaded 的值.(这与 Most Vexing Parse 的当前问题有关.)
What does the indicated line mean? As written, this is a declaration of a member function named confusing that accepts as a parameter an object of type Overloaded (whose name isn't specified in the function declaration) and returns an int. If C++11 were to allow initializers to use parentheses, this would be ambiguous, because it could also be a definition of a member of type int named confusing that is initialized to the value of the data member Overloaded. (This is related to the current issue with the Most Vexing Parse.)
通过要求使用大括号,消除了这种歧义:
By requiring curly braces, this ambiguity is removed:
class BadTimes {
struct Overloaded;
int Overloaded; // Legal, but a very strange idea.
int confusing{Overloaded}; // <-- This line
};
现在,很明显 confusing 实际上是一个 int 初始化为 Overloaded 的值,因为没有办法将它读作函数声明.
Now, it's clear that confusing is actually an int initialized to the value of Overloaded, because there's no way to read it as a function declaration.
希望这有帮助!
这篇关于为什么类内初始化器只能使用 = 或 {}?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么类内初始化器只能使用 = 或 {}?
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
