静态成员初始化期间访问私有静态函数
Access to private static function during static member initialization
我有一个带有静态成员的 class。这将使用相同 class 的私有静态函数进行初始化。
#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;
}
我的问题是:由于哪条规则允许这样做?显然注释部分不起作用,因为不允许我从 class 外部访问私有函数。那么为什么私有静态成员在启动时的初始化是一个特例呢? (附带说明:这条规则的目的是什么?是否允许这种情况?)
我知道初始化静态成员的其他机制(如此处:Initializing private static members)。但在我的例子中,成员是常量,据我所知,唯一的设置方法是在定义的地方直接初始化。
因为静态数据成员的初始化被认为是 class 特征的一部分,即使静态数据成员是在命名空间范围内定义的(在 class 定义之外)。
根据标准,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]
我有一个带有静态成员的 class。这将使用相同 class 的私有静态函数进行初始化。
#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;
}
我的问题是:由于哪条规则允许这样做?显然注释部分不起作用,因为不允许我从 class 外部访问私有函数。那么为什么私有静态成员在启动时的初始化是一个特例呢? (附带说明:这条规则的目的是什么?是否允许这种情况?)
我知道初始化静态成员的其他机制(如此处:Initializing private static members)。但在我的例子中,成员是常量,据我所知,唯一的设置方法是在定义的地方直接初始化。
因为静态数据成员的初始化被认为是 class 特征的一部分,即使静态数据成员是在命名空间范围内定义的(在 class 定义之外)。
根据标准,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 classprocess
inhabits the global scope; the notationprocess::run_chain
indicates that the memberrun_chain
is a member of classprocess
and in the scope of classprocess
. In the static data member definition, the initializer expression refers to the static data memberrunning
of classprocess
. — end example]