c++ - 哪个函数用于初始化静态类成员?

标签 c++ static-members argument-dependent-lookup

我有一个关于选择哪个函数来初始化静态类成员的问题。

//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/

相关文章:

hibernate - Spring 中对实体管理器的静态访问和不寻常的架构

c++ - 参数相关的查找和函数模板

c++ - 通过 TCP 发送 std::vector<float>,从 boost::asio 到 QTcpSocket

c++ - 什么时候在 C++ 中调用模板类的静态成员的构造函数?

c++ - 获取类中静态属性的个数

c++ - 模板库中的名称查找 : why do we add this->

c++ - ADL 未选取带有模板参数列表的后缀表达式

c++ - 如何删除以这种方式创建的缓冲区?

c++ - 从指针指向内存的二进制文件中读取结构

java - 不使用算术运算符的乘法、除法和平方根