首頁 > 後端開發 > C++ > 類別資料成員可以直接在C中初始化嗎?

類別資料成員可以直接在C中初始化嗎?

Barbara Streisand
發布: 2024-11-15 02:14:02
原創
414 人瀏覽過

Can Class Data Members Be Initialized Directly in C++?

Can Class Data Members Be Directly Initialized?

In C++, class data members cannot be initialized using the direct initialization syntax, (), as seen in the following example:

#include <iostream>

class test {
public:
    void fun() {
        int a(3);
        std::cout << a << '\n';
    }
private:
    int s(3);    // Compiler error
};

int main() {
    test t;
    t.fun();
    return 0;
}
登入後複製

The compilation fails with errors:

11    9 [Error] expected identifier before numeric constant
11    9 [Error] expected ',' or '...' before numeric constant
登入後複製

Why is this the case?

The C++ standard explicitly prohibits this syntax for class data member initialization. Early proposals for the feature's introduction cited parsing problems as the reason.

Consider this ambiguous example:

struct S {
    int i(x); // data member with initializer or...
    // ...
    static int x;
    int i(y); // member function declaration
    // ...
    typedef int y;
};
登入後複製

The standard proposes a solution:

To eliminate ambiguity, the C++ standard allows only the following syntax for class data member initialization:

  • = initializer-clause
  • { initializer-list }

This resolution ensures clarity and avoids the potential for misunderstanding in cases where a declaration could resemble both an object and a function declaration.

以上是類別資料成員可以直接在C中初始化嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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