27

给定这个基类:

class Employee
{
     char* name;
     int age;

  public:
     Employee(char* name);
     void print();
};

关于“公众”,这有什么区别:

class Manager : public Employee
{
   EmployeeList employees;

   public:
     Manager(char* name, Employee* people);
     void print();
};

和这个:

class Manager : Employee
{
   EmployeeList employees;

  public:
     Manager(char* name, Employee* people);
     void print();
};
4

3 回答 3

46

The default is private inheritance. take this example:

class B { };
class D: B { };

uses private inheritance as its the default. This means that D gets all the protected and public fields and methods that B has (if we actually declared any), but can't be cast to a B. Therefore, this code fails:

void foo(B* argument) {}
foo(new D);                   //not allowed

If D publicly inherited from B, then a D could be cast to a B, and this function call would be fine.

The second difference is that all the protected and public members in B become private members in D.

What does this actually mean? Public inheritance means D IS_A B, but private inheritance means "is implemented in terms of". Inheriting D from B means you want to take advantage of some of the features in B, but not because D IS_A B or because there's any conceptual connection between B and D. :D

于 2009-10-14T01:16:33.817 回答
3

没有那个“公共”,“员工”将成为“经理”的私有基类。

使用关键字“class”声明的类默认情况下其成员为私有,默认情况下其基类为私有。

使用关键字“struct”声明的类默认情况下其成员是公开的,并且默认情况下其基类是公开的。

于 2009-10-14T01:11:36.110 回答
0

In C++, inheritance is private by default. However, to any code using the Manager class, there appears to be almost no difference, since they have the same methods.

You won't be able to cast the Manager object to an Employee, though. You also won't be able to access the employees variable from within the Manager class.

于 2009-10-14T01:13:42.140 回答