Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
94 views
in Technique[技术] by (71.8m points)

c++ - Why can in-class initializers only use = or {}?

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...