Given codes in language C++
/* file xxx.hpp */
class A
{
};
class B
{
private:
class C
{
static const A a;
};
};
How can I initialize the static constant member variable A a
in nested class C?
Add the following to exactly one .cpp
:
const A B::C::a;
Note that the posted code was only a declaration : this is the actual definition and initialisation.
In the cpp file with code that is to be compiled you should add const AB::C::a = {};
. The initializer (be it an initializer list in {...} for POD classes or aggregate types or a single constant value for built-in types) is optional - if it's not specified, a default constructor will be called for a
. In case of primitive types, it should be set to 0.
updated:
As David has greatly remarked below, some compilers issue warnings when no initializer is specified for a static member definition. If there are some data members in class A
and no initializer during definition of a
is specified, my g++ 4.6.3 compiler issues the following warning (that is by default is treated as error):
test.cpp:26:9: error: uninitialized const 'B::C::a' [-fpermissive]
test.cpp:6:7: note: 'const class A' has no user-provided default
constructor test.cpp:11:8: note: and the implicitly-defined constructor does not initialize 'int A::test'
Like you would a regular static
member.
In your implementation file:
const A B::C::a;
静态成员变量的初始化始终在变量的定义中执行,该变量必须位于程序中的单个翻译单元中:
const A B::C::a = {};
在源文件(xxx.cpp)中,定义变量:
const A B::C::a;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.