在派生中调用多个虚函数 class

Calling multiple virtual functions in a derived class

我正在为 2D 游戏引擎创建场景图。我创建了一个名为 Node 的基础 class,它由 Sprite 派生,而 Sprite 又由 Player 派生。每个 class 都有虚函数 update()。我想调用每个 class 中的每个 update()。我不知道这是否可能(除了使用 base::update(),但对于许多派生的 classes 来说这有点混乱)。

以下代码让我对项目的当前结构有了一些了解。

#include <iostream>

class Base
{
public:
    virtual void print()
    {
        std::cout << "Hello from Base ";
    }
};

class Derived : public Base
{
public:
    virtual void print()
    {
        std::cout << "and Derived!" << std::endl;
    }
};

int main()
{
    Derived foo = Derived();
    foo.print(); // Obviously outputs only "and Derived!"
}

虽然以上完全符合预期,但我想要的输出实际上是 "Hello from Base and Derived!"。

我知道我可以将 Base::print() 放在 Derived::print() 的顶部,但我正在寻找一种更简洁的方法,每个 class 都有许多派生的 classes其他。 我对 C++ 作为一种语言有点陌生,我找不到关于这个主题的信息。如果它不符合适当的多态性,我愿意完全改变我的方法。我宁愿把事情做好,也不愿为了达到这种效果而搞砸。

I know I can put Base::print() at the top of Derived::print(), but I am looking for a method to that's a little cleaner with many derived classes on top of each other.

如果需要,您必须明确地这样做,这就是用多态性覆盖的全部意义。

class Derived : public Base
{
public:
    virtual void print()
    {
        Base::print();
        std::cout << "and Derived!" << std::endl;
    }
};

正如您提到的图表(树状结构),您应该看看 Visitor Pattern

有时 C++ 会做一些您意想不到的事情。

我的建议是使用它必须支持的 C 语言特性。

在这种情况下,我使用union来实现您要的程序化效果:

#include <iostream>

class Base
{
public:
    virtual void print()
    {
        std::cout << "Hello from Base ";
    }
};

class Derived : public Base
{
public:
    virtual void print()
    {
        std::cout << "and Derived!" << std::endl;
    }
};

int main(void);
int main()
{
    Base foo;
    Derived bar;
    union foobar {Base *b; Derived *d;} fb;

    fb.b = &foo; fb.b->print();
    fb.d = &bar; fb.d->print();

    return 0;
}

代码 LINK:http://ideone.com/JdU8T6