在静态成员初始化期间访问私有静态函数

11

我有一个带有静态成员的类,它将使用相同类的私有静态函数进行初始化。

#include <iostream>
#include <string>

class A
{
public:
    static std::string const s;

private:
    static std::string make()
    {
        return "S";
    }
};

std::string const A::s = A::make();

int main()
{
    std::cout << A::s << std::endl;
    // std::cout << A::make() << std::endl; // <-- Does not work
    return 0;
}
我的问题是:这种行为是由哪条规则允许的?显然,注释部分不起作用,因为我不被允许从类外部访问私有函数。那么为什么在启动期间初始化私有静态成员是一个特殊情况呢?(另外一件事:这个规则的意图是什么?是为了允许这种精确的情况吗?)
我知道还有其他机制可以初始化静态成员(比如这里:初始化私有静态成员)。但是在我的情况下,成员是const的,所以据我所知,唯一的设置方式是通过在定义位置进行直接初始化。
1个回答

10
因为静态数据成员的初始化被视为类的特性的一部分,即使静态数据成员在命名空间范围内定义(在类定义之外),它仍然被认为是类的一部分。
从标准 class.static.data#note-1

[Note 1: The initializer in the definition of a static data member is in the scope of its class ([basic.scope.class]). — end note]

[Example 1:

class process {
  static process* run_chain;
  static process* running;
};

process* process::running = get_main();
process* process::run_chain = running;

The definition of the static data member run_­chain of class process inhabits the global scope; the notation process​::​run_­chain indicates that the member run_­chain is a member of class process and in the scope of class process. In the static data member definition, the initializer expression refers to the static data member running of class process. — end example]


1
你关于const的观点是正确的。已编辑问题。谢谢。 - Sven Holzmann
1
我认为这个说法更清晰:“即使静态数据成员在命名空间范围内(类定义外部)被定义,其初始化被视为类的特征描述的一部分。”(我使用“特征描述”是因为“类定义”在C++标准中具有非常正式的含义。) - Martin Bonner supports Monica
@MartinBonner 好的。 - songyuanyao

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接