C 11 introduces in-class initializers, which allow member variables to be initialized directly within the class definition. However, these initializers must adhere to specific syntax rules.
Question:
Why is it mandated that in-class initializers use either the equals sign (=) or curly braces ({})?
Answer:
This requirement serves to eliminate potential syntax ambiguities.
Consider the following example:
class BadTimes { struct Overloaded; int Overloaded; // Legal, but unusual. int confusing(Overloaded); // <-- Ambiguous line };
The problematic line could be interpreted in two ways:
This ambiguity arises due to the use of parentheses, which can denote both method declarations and object initialization.
To resolve this confusion, C 11 mandates the use of curly braces for in-class initializers. This explicitly indicates that confusing is a member variable:
class BadTimes { struct Overloaded; int Overloaded; // Legal, but unusual. int confusing{Overloaded}; // <-- Clear initialization };
Thus, in-class initializers must utilize equals or curly braces to prevent syntax misunderstandings and ensure code readability.
The above is the detailed content of Why Must C In-Class Initializers Use `=` or `{}`?. For more information, please follow other related articles on the PHP Chinese website!