[英]How to call a method that expects a subclass object with an subclass object referenced by a pointer to its superclass?
我有一个由超类指针引用的对象: 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 。
在您的示例中,您可以创建Base类的函数f虚拟成员,并在Derived类中覆盖它。 然后通过指针调用它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();
};
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.