在 C++ 中调用直接父级

gil*_*_mo 0 c++ inheritance

这是一个不断演变的代码的真实故事。我们从基于此结构的许多类开始:

class Base
{
public:
    virtual void doSomething() {}
};

class Derived : public Base
{
public:
    void doSomething() override 
    {
        Base::doSomething(); // Do the basics

        // Do other derived things
    }
};
Run Code Online (Sandbox Code Playgroud)

有一次,我们需要一个介于 Base 和 Derived 之间的类:

class Base;
class Between : public Base;
class Derived : public Between;
Run Code Online (Sandbox Code Playgroud)

为了保持结构,Between::doSomething()首先调用Base。但是现在Derived::doSomething()必须更改为调用Between::doSomething()...

这适用于 Derived 的所有方法,需要搜索和替换许多调用。

最好的解决方案是使用一些 this->std::direct_parent 机制来避免所有替换并允许轻松管理类拓扑。

当然,只有当有一个直接父级时,才应该编译。

有什么办法可以做到这一点吗?如果不是,这可能是 C++ 委员会的功能请求吗?

Tom*_*mek 7

我可以建议的是parenttypedef Derived

class Base
{
public:
    virtual void doSomething() {}
};

class Derived : public Base
{
private:
    typedef Base parent;
public:
    void doSomething() override 
    {
        parent::doSomething(); // Do the basics

        // Do other derived things
    }
};
Run Code Online (Sandbox Code Playgroud)

然后引入之后Between唯一需要的更改Derived是 typedef 的更改parent

class Derived : public Between
{
private:
    typedef Between parent;
public:
    void doSomething() override 
    {
        parent::doSomething(); // Do the basics

        // Do other derived things
    }
};
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这个解决方案,但我不会使用 typedef,而是使用 `using Parent = Between;` (如果您有带有模板的代码库,通常效果会更好一些) (2认同)