gpt4 book ai didi

c++ - 静态成员初始化期间访问私有(private)静态函数

转载 作者:可可西里 更新时间:2023-11-01 16:06:30 29 4
gpt4 key购买 nike

我有一个带有静态成员的类。这将使用同一类的私有(private)静态函数进行初始化。

#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;
}

我的问题是:由于哪条规则允许这样做?显然注释部分不起作用,因为不允许我从类外访问私有(private)函数。那么为什么私有(private)静态成员在启动时的初始化是一个特例呢? (附带说明:这条规则的目的是什么?是否允许这种情况?)

我知道初始化静态成员的其他机制(如此处:Initializing private static members)。但在我的例子中,该成员是常量,据我所知,设置它的唯一方法是在定义位置直接初始化。

最佳答案

因为静态数据成员的初始化被认为是类特征的一部分,即使静态数据成员是在命名空间范围内(在类定义之外)定义的。

来自标准,class.static.data#note-1 :

[Note 1: The initializer in the definition of a static data member isin 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 processinhabits the global scope; the notation process​::​run_­chainindicates that the member run_­chain is a member of class process andin the scope of class process. In the static data member definition,the initializer expression refers to the static data member running ofclass process. — end example]

关于c++ - 静态成员初始化期间访问私有(private)静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38583989/

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