简体   繁体   English

来自私有继承类的C ++虚拟函数,在派生类声明中提升为公共

[英]C++ virtual function from privately inherited class, promoted to public in derived class declaration

I have the following scheme: 我有以下方案:

class Interface
{
    virtual ~Interface() { }
    virtual void foo() const = 0;
    virtual void bar() const = 0;
}

//Interface is derived privately mostly for preventing upcast outside
class Derived : private Interface
{
public:
    void foo() const;
private:
    void bar() const;
}

It does not compile : foo is private. 它不会编译: foo是私有的。 Is there any way to make it public without adding a dummy public function? 有什么办法可以在不添加虚拟公共功能的情况下将其公开?

It is perfectly valid, as far as the language is concerned, for a public member function in a derived class to override a private member function in the base class. 就语言而言,派生类中的公共成员函数覆盖基类中的私有成员函数是完全有效的。 Whether doing so is a good idea is a different question. 这样做是否是一个好主意是另一个问题。 And it certainly makes little sense for an abstract base class to have no public member functions. 对于抽象基类没有公共成员函数当然毫无意义。

The problem with your code is that Interface has a private destructor, making it impossible for derived classes to destroy their base class subobjects. 您的代码的问题在于Interface具有私有析构函数,从而使派生类无法销毁其基类子对象。 ~Interface() should be either protected or public. ~Interface()应该是受保护的或公共的。

No, there is not. 不,那里没有。

Furthermore, even a dummy public function would require that foo in the base were protected , not private . 此外,即使是虚拟的公共功能也将要求基本中的foo protected ,而不是private

I would revisit your design. 我会重新审视您的设计。 If the function is intended to be public, then why is it not public ? 如果该功能旨在公开,那么为什么不public呢?

It is not allowed to change the accessibility of an inherited member. 不允许更改继承成员的可访问性。 If it was allowed, you would be able to derive from a class and make its private or protected members public, breaking the encapsulation. 如果允许,您将能够从一个类派生并将其私有或受保护的成员公开,从而打破封装。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM