【问题标题】:Which function is used to initialize the static class member?哪个函数用于初始化静态类成员?
【发布时间】:2013-07-17 09:22:20
【问题描述】:

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

//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=countInit(); 给会员打电话?
  • @LuchianGrigore,是的,确实如此。我不知道发生了这种情况。
  • “int Base::count=countInit();”在哪里被调用?导致静态成员函数 Base::countInit() 计数不能仅由 countInit() 调用,超出类 Base 的范围。
  • 试试 ::countInit(),有什么不同吗?
  • @NeilKirk 如果调用 ::countInit(),则使用本地 countInit。

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


【解决方案1】:

写完int Base::count后,你就在Base类中,所以类的静态函数会被调用。 此处将使用不合格的查找

从 3.4.2/13

用于定义类 X (9.4.2) 的静态数据成员的名称(在静态的限定 ID 之后) member) 被查找,就好像该名称已在 X 的成员函数中使用一样。

从 9.4.2

静态数据成员的定义应出现在命名空间中 包含成员的类定义的范围。在命名空间范围的定义中,静态的名称 数据成员应使用 :: 运算符由其类名限定。 中的初始化表达式 静态数据成员的定义在其类的范围内

例子:

class process {
static process* run_chain;
static process* running;
};
process* process::running = get_main();
process* process::run_chain = running;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 2011-07-18
    • 2015-05-18
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多