In C , class data members cannot be initialized using the direct initialization syntax, (), as seen in the following example:
#includeclass test { public: void fun() { int a(3); std::cout The compilation fails with errors:
11 9 [Error] expected identifier before numeric constant 11 9 [Error] expected ',' or '...' before numeric constantWhy 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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3