使用“公共”在派生类声明中? [英] Use of "Public" in a derived class declaration?

查看:153
本文介绍了使用“公共”在派生类声明中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定此基类:

  class Employee 
{
char * name;
int age

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

对于public,这之间有什么区别:

 类经理: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();
};


解决方案

默认是私有继承。以此为例:

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

使用私有继承作为默认值。这意味着D得到B拥有的所有受保护和公共字段和方法(如果我们实际上声明任何),但不能转换为B.因此,此代码失败:

  void foo(B * argument){} 
foo(new D); //不允许

如果D从B公开继承,那么D可以转换为B,



第二个区别是B中的所有受保护和公共成员都成为D中的私有成员 / p>

这是什么意思?公共继承意味着D IS_A B,但私有继承意味着以...实现。从B继承D意味着你想利用B中的一些功能,但不是因为D IS_A B,或者因为B和D之间有任何概念上的连接:D


Given this base class:

class Employee
{
     char* name;
     int age;

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

With regards to the "public", what's the difference between this:

class Manager : public Employee
{
   EmployeeList employees;

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

and this:

class Manager : Employee
{
   EmployeeList employees;

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

解决方案

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

这篇关于使用“公共”在派生类声明中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆