为什么类的初始化器只使用=或{}? [英] Why can in-class initializers only use = or {}?
问题描述
课程初始设定(C ++ 11功能)必须以卷曲形式大括号或遵循a =符号。
这是什么原因?
我不是100%积极的这一点,但这可能是为了防止语法歧义。例如,考虑以下类:
class BadTimes {
struct Overloaded;
int重载; //法律,但一个很奇怪的想法。
int confusing(Overloaded); //< - this line
};
指示的行是什么意思?如所写的,这是一个名为的成员函数的声明,该函数接受
Overloaded
(<其名称未在函数声明中指定),并返回 int
。如果C ++ 11允许初始化器使用括号,这将是不明确的,因为它也可以是 int
类型的成员的定义混淆
,它被初始化为数据成员 Overloaded
的值。 (这与最常见解析解析的当前问题相关。)
通过要求花括号,这个歧义被删除:
class BadTimes {
struct Overloaded;
int重载; //法律,但一个很奇怪的想法。
int confusing {Overloaded}; //< - this line
};
现在,很清楚,混淆
一个 int
初始化为重载
的值,因为没有办法读取它作为函数声明。 >
希望这有助于!
In-class initializers (C++11 feature) must be enclosed in curly braces or follow a = sign. They may not be specified inside parenthesis.
What is the reason for this?
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
};
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
};
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.
Hope this helps!
这篇关于为什么类的初始化器只使用=或{}?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!