【问题标题】:call an immediate parent in c++在 C++ 中调用直接父级
【发布时间】:2022-11-24 17:27:17
【问题描述】:

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

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

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

        // Do other derived things
    }
};

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

class Base;
class Between : public Base;
class Derived : public Between;

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

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

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

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

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

【问题讨论】:

标签: c++ inheritance


【解决方案1】:

我可以建议的是 parentDerived 中的 typedef:

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
    }
};

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

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

        // Do other derived things
    }
};

【讨论】:

  • 我喜欢这个解决方案,但我会使用 using parent = Between; 而不是 typedef(如果你有带有模板的代码库,通常会更好一些)
【解决方案2】:

我认为这个问题与:Using "super" in C++有关

我见过一些项目,在这些项目中,当前类的直接父级在类头中被称为“SUPER”typedef。这使得使用新的中间类进行代码更改更加容易。不防弹,但更容易。与链接问题中的几乎相同。

【讨论】:

  • 以 Tomek 的回答为例
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-04
相关资源
最近更新 更多