我有一个关于 C++ 双重调度的问题。在下面的代码中,我希望第二组的结果与第一组的结果相匹配。
我不知道实际类型(除非我尝试 dynamic_cast),但我知道该对象继承自 BaseClass 类型。实现这一目标的最有效(性能方面)的方法是什么?
在谷歌搜索了一段时间后,我发现了双重调度和 loki 多方法。我在 Shape 示例中遇到的问题是,在我的应用程序中,Processor 和 BaseClass 是完全独立的,并且没有可以相互调用的通用方法。其次,只有一个处理器(即没有任何东西继承自它)。
谢谢你的帮助。
#include <iostream>
#include <string>
using namespace std;
class BaseClass{
public:
BaseClass(){}
virtual void myFunction(){cout << "base myFunction called" << endl;}
};
class Derived1: public BaseClass{
public:
Derived1():BaseClass(){}
void myFunction(){cout << "Derived1 myFunction called" << endl;}
};
class Derived2: public BaseClass{
public:
Derived2():BaseClass(){}
void myFunction(){cout << "Derived2 myFunction called" << endl;}
};
class Derived3: public BaseClass{
public:
Derived3():BaseClass(){}
void myFunction(){cout << "Derived3 myFunction called" << endl;}
};
class Processor{
public:
Processor(){}
virtual void processObj(BaseClass* bc){cout << "got a base object" << endl; bc->myFunction();}
virtual void processObj(Derived1* d1){cout << "got a derived1 object" << endl; d1->myFunction();}
virtual void processObj(Derived2* d2){cout << "got a derived2 object" << endl; d2->myFunction(); }
};
int main() {
BaseClass *bcp=new BaseClass();
Derived1 *dc1p=new Derived1();
Derived2 *dc2p=new Derived2();
Derived3 *dc3p=new Derived3();
Processor p;//can also use Processor* p = new Processor()
//first set results
p.processObj(bcp);
p.processObj(dc1p);
p.processObj(dc2p);
p.processObj(dc3p);
BaseClass *bcp1=bcp;
BaseClass *dc1p1=dc1p;
BaseClass *dc2p1=dc2p;
BaseClass *dc3p1=dc3p;
//second set results
p.processObj(bcp1);
p.processObj(dc1p1);
p.processObj(dc2p1);
p.processObj(dc3p1);
return 0;
}