初始化私有静态成员 [英] Initializing private static members
问题描述
在C ++中初始化私有静态数据成员的最好方法是什么?我试过这个,但它给我怪异的链接器错误:
What is the best way to initialize a private, static data member in C++? I tried this but it gives me weird linker errors:
class foo
{
private:
static int i;
};
int foo::i = 0;
我猜这是因为我无法从类外部初始化一个私人成员。那么这是最好的方法是什么?
I'm guessing this is because I can't initialize a private member from outside the class. So what's the best way to do this?
推荐答案
类声明应该在头文件不共享)。
文件:foo.h
The class declaration should be in the header file (Or in the source file if not shared).
File: foo.h
class foo
{
private:
static int i;
};
但初始化应在源文件中。
文件:foo.cpp
But the initialization should be in source file.
File: foo.cpp
int foo::i = 0;
如果初始化在头文件中,那么包含头文件的每个文件将具有静态成员。因此,在链接阶段,您会得到链接器错误,因为初始化变量的代码将在多个源文件中定义。
If the initialization is in the header file then each file that includes the header file will have a definition of the static member. Thus during the link phase you will get linker errors as the code to initialize the variable will be defined in multiple source files.
注意: Matt Curtis:指出,如果静态成员变量是const int类型,则C ++允许简化上述操作(例如 int
, bool
, char
)。然后,您可以直接在头文件中的类声明中声明和初始化成员变量:
Note: Matt Curtis: points out that C++ allows the simplification of the above if the static member variable is of const int type (e.g. int
, bool
, char
). You can then declare and initialize the member variable directly inside the class declaration in the header file:
class foo
{
private:
static int const i = 42;
};
这篇关于初始化私有静态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!