我怎样才能动态地调用表单的函数:childA.function(childB)
而它们的静态类型都是父母?
并提供更多详细信息:
我有一个物理项目,我需要计算 2 个分子的势能。但是我有两种类型的分子,LC 和 Col,每种类型都有自己的参数和东西,但是我希望能够动态地调用每个分子的潜力。
所以我尝试了这个:
#include <iostream>
#include <typeinfo>
#include <stdio.h>
using namespace std;
class Col;
class LC;
class Molecule
{
public:
/// more data and functions should be here regarding the molecule
double someBulshit;
virtual double potential(const Molecule * mol){}
virtual double potential(const Col * mol){}
virtual double potential(const LC * mol){}
};
class LC : public Molecule
{
public:
/// more data and functions should be here regarding the LC molecule
virtual double potential(const Molecule * mol) {return 1;}
virtual double potential(const LC * mol) {return 2;}
virtual double potential(const Col * mol) {return 3;}
};
class Col : public Molecule
{
public:
/// more data and function should be here regarding the Col molecule
virtual double potential(const Molecule * mol) {return 4;}
virtual double potential(const LC * mol) {return 5;}
virtual double potential(const Col * mol) {return 6;}
};
int main(int argc, char* argv[])
{
Molecule * mol1 = new Col();
Molecule * mol2 = new LC();
double my_potential = mol1->potential(mol2);
printf ("%f",my_potential);
}
但是我得到了 4 的结果,因为事实证明该函数是静态调用的,这意味着由于 mol1 的静态类型是 Molecule,所以调用的函数是:
virtual double potential(const Molecule * mol) {return 4;}
并不是
virtual double potential(const LC * mol) {return 5;}
无论如何在不使用 typeid 的情况下动态调用函数(在 OOP 设计中)?
完整答案:
在 Peter 的建议下进行调查后,这被证明是经典的双重调度问题,完整的解决方案就是在虚拟内部调用另一个虚拟,如下所示:
#include <iostream>
#include <typeinfo>
#include <stdio.h>
using namespace std;
class Col;
class LC;
class Molecule
{
public:
/// more data and functions should be here regarding the molecule
double someBulshit;
virtual double potential(const Molecule * mol) const = 0;
virtual double potential(const Col * mol) const = 0;
virtual double potential(const LC * mol) const = 0;
};
class LC : public Molecule
{
public:
/// more data and functions should be here regarding the LC molecule
virtual double potential(const Molecule * mol) const {return mol->potential(this);}
virtual double potential(const LC * mol) const {return 2;}
virtual double potential(const Col * mol) const {return 3;}
};
class Col : public Molecule
{
public:
/// more data and function should be here regarding the Col molecule
virtual double potential(const Molecule * mol) const {return mol->potential(this);}
virtual double potential(const LC * mol) const {return 5;}
virtual double potential(const Col * mol) const {return 6;}
};
int main(int argc, char* argv[])
{
Molecule * mol1 = new Col();
Molecule * mol2 = new LC();
double my_potential = mol1->potential(mol2);
printf ("%f",my_potential);
}
这确实根据需要返回 3 。