问题描述
类内初始化器(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.
希望这有帮助!
这篇关于为什么类内初始化器只能使用 = 或 {}?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!