为什么我们可以在其类范围之外定义私有成员

St.*_*rio 0 c++ static

我认为私有成员甚至不存在于类范围之外,所以我们无法访问它们.但考虑一下:

#include <iostream>

class A
{
private:
    static const int a = 1;
};

const int A::a; //Access to the private member outside the class scope
                //the compiler doesn't compain

int main ()
{
    std::cout << A::a << std::endl; //compile-time error
}
Run Code Online (Sandbox Code Playgroud)

为什么允许?这只是为了方便吗?

AnT*_*AnT 5

这是允许的,因为语言标准是这样说的.

在访问说明符的帮助下实现的成员访问控制的概念private与对成员定义施加限制完全无关.它是为了完全不同的目的而引入的.它旨在限制完全不同的上下文中的访问.语言规范不禁止在课堂外定义私人成员.为什么会这样?

您对私有成员的描述在类范围之外"甚至不存在"是完全错误的.语言标准实际上明确地说明了类的受保护和私有成员在类外部是完全可见的,甚至可以通过名称查找找到.仅在此之后检查访问限制.

例如,在一段代码中,如下所示

struct S {
    void foo(long);
private:
    void foo(int);
};

int main() {
    S().foo(1);
}
Run Code Online (Sandbox Code Playgroud)

编译器需要S::foo(int)从外部查看私有,通过重载解析选择它,然后告诉您正在尝试调用私有函数.