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

时间:2015-06-19 05:00:36

标签: 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
}

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

2 个答案:

答案 0 :(得分:5)

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

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

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

E.g。在一段代码中,如下所示

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

int main() {
    S().foo(1);
}

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

答案 1 :(得分:1)

#include <iostream>

class A
{
private:
    /* an in-class initialization, which is only allowed if the
     * data member is static const and is of integral type.
     */
    static const int a = 1;
};

const int A::a; // a definition, not an "access".
/* The above line will actually incur a "duplicate initialization"
 * compile-time error, because the data member a has already been
 * defined in the class.
 */

int main ()
{
    std::cout << A::a << std::endl; // compile-time error
}