如何从一个基类中公开继承,但在派生类中使一些来自基类的公共方法私有? [英] How to publicly inherit from a base class but make some of public methods from the base class private in the derived class?

查看:196
本文介绍了如何从一个基类中公开继承,但在派生类中使一些来自基类的公共方法私有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如, Base 有两个公共方法: foo() bar ()。类派生从类 Base 继承。在 Derived 中,我想让 foo() public但 bar code> private。以下代码是否正确和自然地执行此操作?

For example, class Base has two public methods: foo() and bar(). Class Derived is inherited from class Base. In class Derived, I want to make foo() public but bar() private. Is the following code the correct and natural way to do this?

class Base {
   public:
     void foo();
     void bar();
};

class Derived : public Base {
   private:
     void bar();
};


推荐答案

C ++ '03标准的第11.3节描述了这种能力:

Section 11.3 of the C++ '03 standard describes this ability:


11.3访问声明

基类的
成员的访问权限可以更改
在派生类中声明它的
限定id在派生类
声明。这种提及被称为
访问声明。
访问声明的效果qualified-id;是
,定义为等同于使用qualified-id的
声明

11.3 Access declarations
The access of a member of a base class can be changed in the derived class by mentioning its qualified-id in the derived class declaration. Such mention is called an access declaration. The effect of an access declaration qualified-id ; is defined to be equivalent to the declaration using qualified-id


注意:从ISO C ++ '11开始,访问声明( Base :: bar; / code>)被禁止,如评论中所述。应该使用一个使用声明(使用Base :: bar; )。

1)您可以使用公共继承,然后将栏设为私人:

1) You can use public inheritance and then make bar private:

class Base {
public:
    void foo(){}
    void bar(){}
};

class Derived : public Base {
private:
    using Base::bar;
};

2)可以使用私有继承,然后使foo public:

2) You can use private inheritance and then make foo public:

class Base {
public:
    void foo(){}
    void bar(){}
};

class Derived : private Base {
public:
    using Base::foo;
};

注意:如果你有一个类型为Base的指针或引用,其中包含Derived类型的对象,用户仍然可以调用该成员。

Note: If you have a pointer or reference of type Base which contains an object of type Derived then the user will still be able to call the member.

这篇关于如何从一个基类中公开继承,但在派生类中使一些来自基类的公共方法私有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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