In-Class Data Member Initialization Anomaly: Delving into the C++ Standard
Unlike local data members that can be directly initialized with the () syntax, in-class data members defy this convenient method. This peculiarity has perplexed many programmers, prompting questions about its underlying rationale.
According to the C++ standard, direct initialization of class data members using () is prohibited to prevent parsing ambiguity. Consider the following scenario:
class S { public: int i(x); // data member with initializer };
Without the restriction, the compiler could become perplexed when trying to determine whether the declaration refers to a data member with an initializer or a member function declaration.
For instance:
struct S { int i(j); // member function declaration int j; // data member without an initializer };
Applying the existing parsing rule that prioritizes member functions over data members in ambiguous situations could lead to incorrect interpretations. To avoid such confusion, the C++ standard opted to disallow direct initialization of class data members.
Nevertheless, alternative initialization methods remain available, such as using the = initializer-clause syntax:
int s = 3;
Or the initializer-list wrapped in curly braces:
int s{3};
By adhering to these methods, programmers can effectively initialize class data members, albeit with a different syntax than their local counterparts.
以上是為什麼我們不能使用括號來初始化 C 中的類別內資料成員?的詳細內容。更多資訊請關注PHP中文網其他相關文章!