继承子类时的默认保护级别是什么?

时间:2011-06-05 20:31:30

标签: c++ inheritance

  

可能重复:
  Default class inheritance access

我知道我可以在从超类声明子类时设置保护级别,如下所示:

class Dog : public Pet {
   *blah, blah, blah*
}

但在这种情况下,保护级别默认为什么?

Class Dog: Pet {
   *blah, blah, blah*
}

1 个答案:

答案 0 :(得分:6)

对于一个类,它是私有的

class Dog: Pet  // Pet is inherited privately.
{}

对于结构,它是公开的。

struct Dog: Pet  // Pet is inherited publicly.
{}

简单测试:

class Pet {};
class  DogClass:  Pet {};
struct DogStruct: Pet {};
int main()
{
    DogClass   dogClass;
    // Pet&       pet1 = dogClass;  This line will not compile.

    DogStruct  dogStruct;
    Pet&       pet2 = dogStruct;
}