【发布时间】:2014-09-25 21:36:23
【问题描述】:
我最近想让 c++ 通过其输入参数动态解析成员/函数,该输入参数出现在某些派生版本中。这就是我的意思:
#include <iostream>
class Base {
};
class DerivedA : public Base {
};
class DerivedB : public Base {
};
class DerivedC : public Base {
};
class Test {
public:
void world( DerivedA *instance )
{
std::cout << "DerivedA" << std::endl;
}
void world( DerivedB *instance )
{
std::cout << "DerivedB" << std::endl;
}
void world( Base *instance )
{
std::cout << "Base" << std::endl;
}
};
int main()
{
Base *a = new Base;
Base *b = new DerivedA;
Base *c = new DerivedB;
Base *d = new DerivedC;
Test hello;
hello.world( a );
hello.world( b );
hello.world( c );
hello.world( d );
return 0;
}
我想要的行为是这样的:
Base
DerivedA
DerivedB
Base
但可以肯定的是,我真正得到的输出是这样的:
Base
Base
Base
Base
我知道,动态绑定是另一种方式,在基类的派生类中解析正确的成员函数,而不是那样 - 但它可以以任何方式工作吗?
也许我只是错过了要点..
不过,提前非常感谢!
塞巴斯蒂安
【问题讨论】:
-
这里的用例是什么?我不明白为什么不能简单地将每个变量定义为相应的派生类型而不是
Base。获得所需功能的唯一方法是使用dynamic_cast<>。 -
您将
Base*传递给所有这些函数。您需要使用 virtual functions 来实现您想要实现的目标(您必须将world函数设为成员函数)。 -
@RedAlert:您还需要至少有一个虚拟成员函数,然后执行
if(dynamic_cast<X>(instance) { ... }- 这两者可能比一开始调用虚拟函数更耗时。 -
首先,这背后的意义是,实例是在其他函数中创建的,但是在我想从“测试”类运行不同代码的地方,我无法确定每个实例是哪个类对象是一个实例。我知道,我可以像 Mats Petersson 所说的那样做,但我想将代码保留在测试类中,而不是对象中。
-
我现在能想到的一个解决方案(我可能会在几个小时或几天内想出其他东西)是添加一个包装类。让我把它写下来......
标签: c++ rtti dynamic-binding