c++ - 从抽象(纯虚拟)类私有(private)继承是否有意义?

标签 c++ abstract-class virtual-functions private-inheritance

假设这个结构

struct InterfaceForFoo
{
    virtual void GetItDone() = 0;
};


class APoliticallyCorrectImplementationOfFooRelatedThings : private InterfaceForFoo
{

  public:
    void GetItDone() { /*do the thing already*/ };   
};

现在,我想知道以这种方式从接口(interface)私有(private)继承是否有任何有用的场景。

最佳答案

哈,这里的每个人都说“不”。我说“是的,它确实有意义。”

class VirtualBase {
public:
    virtual void vmethod() = 0;
    // If "global" is an instance of Concrete, then you can still access
    // VirtualBase's public members, even though they're private members for Concrete
    static VirtualBase *global;
};

// This can also access all of VirtualBase's public members,
// even if an instance of Concrete is passed in,
void someComplicatedFunction(VirtualBase &obj, ...);

class Concrete : private VirtualBase {
private:
    virtual void vmethod();
public:
    void cmethod() {
        // This assignment can only be done by Concrete or friends of Concrete
        VirtualBase::global = this;
        // This can also only be done by Concrete and friends
        someComplicatedFunction(*this);
    }
};

使继承private并不意味着你不能从类外访问VirtualBase的成员,它只意味着你不能访问那些成员通过对 Concrete 的引用。但是,Concrete 及其 friend 可以将 Concrete 的实例转换为 VirtualBase,然后任何人都可以访问公共(public)成员。简单地说,

Concrete *obj = new Concrete;
obj->vmethod(); // error, vmethod is private

VirtualBase *obj = VirtualBase::global;
obj->vmethod(); // OK, even if "obj" is really an instance of Concrete

关于c++ - 从抽象(纯虚拟)类私有(private)继承是否有意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6642777/

相关文章:

c++ - std::filesystem "root_name"定义在 Windows 上损坏

c++ - 析构函数在 C++ 中是如何工作的

java - 在 Java 中使用抽象类

抽象类的C++工厂方法模式

协变虚函数的 C++ 规则

c++ - 从虚拟方法返回派生对象作为基础

c++ - 获取视频时长

c++ - 后续: What exactly is a variable in C++14/C++17?

java - 为什么在java中嵌套抽象类

c++ - 覆盖具有多个签名的 C++ 虚拟方法