简体   繁体   English

C ++-私有数据成员

[英]C++ - private data members

If I have a class with private data members, for example, do I say that those data members are not accessible outside the class or they are not accessible outside the objects of that class? 例如,如果我有一个包含private数据成员的类,我是说那些数据成员在类之外是不可访问的,或者在该类的objects之外是不可访问的?

Thanks. 谢谢。

Technically speaking, none of the above. 从技术上讲,以上都不是。 You say, "Only entities that have private access to this class can access these variables." 您说:“只有拥有此类私有访问权限的实体才能访问这些变量。”

This includes objects of that type , member functions of that type, friends of that type , member functions of friends of that type... 这包括 该类型的对象,该类型的 成员函数,该类型的 朋友,该类型 的朋友的成员函数...

Actually, technically speaking, objects are incapable of accessing anything since they do not have behavior. 实际上,从技术上讲,对象无权访问任何东西,因为它们没有行为。

private意味着类的成员函数(以及任何嵌套类型)可以在给定类的任何实例的情况下访问那些数据成员。

If it is private, then (emphasis added): 如果它是私有的,那么(添加了强调):

its name can be used only by members and friends of the class in which it is declared. 它的名称只能由声明它的类的成员和朋友使用。

-- Stroustup's "The C++ Programming Language", and one of the draft standards. -Stroustup的“ C ++编程语言”,也是标准草案之一。

In C++, the data itself can always be accessed by other mechanisms. 在C ++中,数据本身始终可以由其他机制访问。 The goal is to impede accidental access, even if malicious access is still feasible. 目标是即使恶意访问仍然可行,也可以阻止意外访问。

They are not accessible outside the class's code (including derived classes); 在类代码(包括派生类)之外无法访问它们; except for entities declared friend . 声明为friend实体除外。 As the class's code (the class member functions) are bound to the class (not the individual object), accessibility is evaluated at the class level. 由于将类的代码(类成员函数)绑定到类(而不是单个对象),因此在类级别评估可访问性。

class Foo
{
private:
    int secret;
    Foo * other;

public:
    explicit Foo(Foo* other_) : other(other_), secret(42) {}
    Foo() : other(0), secret(0) {}

    int Peek(void) { return secret; }
    int neighborPeek(void)
    {
        if (other)
            return other->secret; // this is OK, we're still inside the class
        else
            return -1;
}

int main()
{
    Foo aFoo, bFoo(&aFoo);
    std::cout << bFoo.neighborPeek(); // will dump aFoo's secret.

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM