我有一个对象被指向其超类的指针引用: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?
}发布于 2016-10-28 20:29:29
一般来说,你可以用dynamic_cast做一些事情。
从另一方面来说,我相信,dynamic_cast实际上总是可以通过良好的设计来避免的。
在您的示例中,您可以使函数f为基类的虚拟成员,并在派生类中重写它。然后通过指向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();
};
};https://stackoverflow.com/questions/40312661
复制相似问题