c ++访问说明符的理解

时间:2017-08-22 11:43:53

标签: c++ access-specifier

我在一个帖子中遇到了以下响应:

可以从派生类访问受保护的成员。私人不能。

class Base {

private: 
  int MyPrivateInt;
protected: 
  int MyProtectedInt;
public:
  int MyPublicInt;
};

class Derived : Base
{
public:
  int foo1()  { return MyPrivateInt;} // Won't compile!
  int foo2()  { return MyProtectedInt;} // OK  
  int foo3()  { return MyPublicInt;} // OK
};

class Unrelated 
{
private:
  Base B;
public:
  int foo1()  { return B.MyPrivateInt;} // Won't compile!
  int foo2()  { return B.MyProtectedInt;} // Won't compile
  int foo3()  { return B.MyPublicInt;} // OK
};

...

1)我的问题是: 我读过:“类派生列表命名了一个或多个基类,其格式为:

class derived-class:access-specifier base-class

其中access-specifier是public,protected或private之一,而base-class是先前定义的类的名称。如果未使用访问说明符,则默认情况下它是私有的。 “和”私有继承:从私有基类派生时,基类的公共成员和受保护成员将成为派生类的私有成员。

SO ...在我们的示例类中Derived:Base相当于类Derived:private Base,因为没有定义访问说明符,但代码工作正如编写者所说,所以我缺少什么? - 我认为类Derived访问说明符的基类是私有因此Base的公共成员和受保护成员对于Derived类应该是私有的,并且无法访问...谢谢!

1 个答案:

答案 0 :(得分:0)

它是一种类似的想法。它不是应用于您可以访问的类的成员,而是适用于您可以访问的基类。

class A
{
public:
    void f();
};



class B : public A
{
public:
    void g()
    {
        f(); // OK
        A *a = this; // OK
    }
};
class B2 : public B
{
public:
    void h()
    {
        f(); //OK
        A *a = this; // OK
    };
};
B b;
A& ba = b;


class C : protected A
{
public:
    void g()
    {
        f(); // OK, can access protected base
        A *a = this; // OK, can access protected base
    }
};
class C2 : public C
{
public:
    void h()
    {
        f(); // OK, can access protected base
        A *a = this; // OK, can access protected base
    };
};
C c;
c.f(); // Not OK, allthough A::f() is public, the inheritance is protected.
A& ca = c; // Not OK, inheritence is protected.




class D : private A
{
public:
    void g()
    {
        f(); // OK because A is a base of D
        A *a = this;
    }
};
class D2 : public D
{
public:
    void h()
    {
        f(); //Not OK, A is inherited with private in D
        A *a = this; //Not OK
    };
};
D d;
d.f(); // Not OK, allthough A::f() is public, the inheritance is private.
D& da = d; // Not OK, inheritence is private.