gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:58:56 24 4
gpt4 key购买 nike

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

//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 staticmember) 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 namespacescope enclosing the member’s class definition. In the definition at namespace scope, the name of the staticdata member shall be qualified by its class name using the :: operator. The initializer expression in thedefinition 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com