如何可以調用形式爲childA.function(childB)
的函數,而它們的靜態類型都是父級?如何使用多態性參數動態調用函數
,並與更多的細節:
我有一個物理項目,我需要計算2個分子的潛力。我有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的是分子調用的函數爲:
virtual double potential(const Molecule * mol) {return 4;}
,而不是
virtual double potential(const LC * mol) {return 5;}
反正是有調用函數DYNA mically(在OOP設計中)不使用typeid?
完整的答案:
與彼得的意見調查後,這變成是經典的雙調度問題的全面解決方案只是調用另一個虛擬的虛擬裏面是這樣的:
#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。
你的源代碼不會編譯。罪魁禍首是「分子」成員職能。您可能還想重命名「Molecule」數據成員。也許你忘了做這些純粹的虛擬?函數不是staticly_。請提供[MCVE](https://stackoverflow.com/help/mcve)。 – Ron
查看訪客模式。 – Peter