首頁 > 後端開發 > C++ > 為什麼我們不能使用括號來初始化 C 中的類別內資料成員?

為什麼我們不能使用括號來初始化 C 中的類別內資料成員?

Barbara Streisand
發布: 2024-11-15 13:44:02
原創
282 人瀏覽過

Why Can\'t We Use Parentheses to Initialize In-Class Data Members in C++?

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板