我有一个关于选择哪个函数来初始化静态类成员的问题。
//Base.h
class Base
{
private:
static int count;
static int countInit()
{
return 10;
}
public:
Base()
{
}
};
//and Base.cpp
static int countInit()
{
return 0;
}
int Base::count=countInit();//member function is used.
static int local_count=countInit();//the local one in Base.cpp
变量 Base::count
是用 Base::countInit()
而不是 Base.cpp 中定义的 countInit()
初始化的.但是 local_count
是由本地 countInit
初始化的。那么,我想知道,在这种情况下是否有像 Koenig 查找 这样的规则?
最佳答案
写完int Base::count
后你就在Base
类中,所以类的静态函数会被调用。 此处将使用不合格的查找
从 3.4.2/13
A name used in the definition of a static data member of class X (9.4.2) (after the qualified-id of the static member) is looked up as if the name was used in a member function of X.
从 9.4.2
The definition for a static data member shall appear in a namespace scope enclosing the member’s class definition. In the definition at namespace scope, the name of the static data member shall be qualified by its class name using the :: operator. The initializer expression in the definition of a static data member is in the scope of its class
Example:
class process { static process* run_chain; static process* running; }; process* process::running = get_main(); process* process::run_chain = running;
关于c++ - 哪个函数用于初始化静态类成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17695943/