如何从一个基类中公开继承,但在派生类中使一些来自基类的公共方法私有?
例如, 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.