c++ - 如何调用一个方法,该方法需要一个子类对象,子类对象由指向其父类(super class)的指针引用?

标签 c++ casting polymorphism

我有一个由指向其父类(super class)的指针引用的对象:Base* d1 = new Derived();

我想将它传递给另一个需要派生类对象的方法:void f(Derived* d);

但除非我使用类型转换,否则它不起作用。还有其他方法可以实现吗?

这是一个例子:

#include <stdio>
class Base {};
class Derived : public Base {};

class Client
{
   public:
   void f(Base* b) { printf("base"); };
   void f(Derived* d) { printf("derived"); };
};

int main(int argc, char* argv[])
{
   Client*  c  = new Client();
   Base*    b  = new Base();
   Base*    d1 = new Derived();
   Derived* d2 = (Derived*) d1;

   c->f(b);  // prints "base". Ok.
   c->f(d1); // prints "base"! I expected it to be "derived"!
   c->f(d2); // prints "derived". Type-casting is the only way?
}

最佳答案

一般来说,您可以使用dynamic_cast 做一些事情。

从另一方面来说,我相信,dynamic_cast 实际上总是可以通过良好的设计来避免。

在您的示例中,您可以使函数 f 成为 Base 类的虚拟成员,并在 Derived 类中覆盖它。然后通过指向 Base 的指针调用它 f

像这样:

class Base {
    public:
        virtual void f() {
            printf("Base\n");
        }
};

class Derived : public Base {
    public:
        virtual void f() {
            printf("Derived\n");
        }
};

class Client
{
   public:
       void f(Base* b) {
           b->f();
       };
};

关于c++ - 如何调用一个方法,该方法需要一个子类对象,子类对象由指向其父类(super class)的指针引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40312661/

相关文章:

c++ - Qt 多用户界面

c++ - 从友元函数访问静态变量

C++ 指向不同类型的指针

javascript - 在 TypeScript 中将数字转换为字符串

c++ - 类型转换 char* -> QString,可读性还是清晰度? (C++/Qt)

c++ - 数组内存分配不起作用

c++ - Qt窗口框架设计

c - 打包的相同结构是否保证具有相同的内存布局?

c++ - 使用指针基类的 =operator 的多态性

c++ - QObject 的多重继承