對於我的畢業論文,我正在編寫一些有限元代碼,或者更準確地說,我正在修改一個現有的程序,它基於2個類庫我的教師。因此,我無法修改這些類,因爲這些類是普遍的。C++:error:'class'沒有名字的成員
我創建了一個類BurgersMSrc
,它從父類ValSrc
繼承。我用一種方法calcFourierCoefficient
擴大了孩子班級。在編譯的時候我收到以下錯誤:
burgers1d.cpp:268:12: error: ‘class ValSrc’ has no member named ‘calcFourierCoefficient’
這是有道理的,因爲變量定義爲:
ValSrc* srcTerm;
不具有定義的方法。後來該變量的實例化依賴於問題類型,其中被實例化爲任
srcTerm = new ConstVS(f);
或
srcTerm = new BurgersMSrc(prm);
。有條件地限定srcTerm
如任一ConstVS
或BurgersMSrc
對象收率:
error: ‘srcTerm’ was not declared in this scope
即不是一種選擇任一。
所以最後我的問題是:
If a variable is defined as a parent class, but instantiated as a child class, how do I access the child's method(s)?
任何幫助真的讚賞,並提前爲您解答感謝。
編輯
通知你,我不是很用C++經驗,但我有在C#和VBA編程的經驗。然而,我喜歡學習,所以朝着正確的方向指針非常歡迎:)
/編輯更
相關的代碼行從頭文件:
#ifndef BurgersMSS_H
#define BurgersMSS_H
#include "mfem.hpp"
#include "mex.h"
class BurgersMSol: public ValSrc
{
...
};
class BurgersMSrc: public ValSrc
{
public:
typedef ValSrc Super;
BurgersMSrc(ParamDB &prm) {init(prm);}
virtual void init(ParamDB &prm);
~BurgersMSrc(){}
inline void getValues (Vector &coords, Vector &msrc){}
void calcFourierCoefficient(int p){}
private:
double nu;
double Tn;
int prob;
int nTimeSteps;
int specModes;
double s_n;
double tT;
double deltaT;
vector <double> a_re;
vector <double> a_im;
int accuracy;
double randomNr;
double randomNumber(int p){return randomNr;}
};
#endif
從相關線在CPP文件:
#include "BurgersMSS.h"
void BurgersMSol::init(ParamDB &prm)
{
...
}
BurgersMSol::~BurgersMSol(){}
inline void BurgersMSol::getValues (Vector &coords, Vector &msol)
{
...
}
BurgersMSrc::init(ParamDB &prm)
{
Super::init(); objectName="BurgersMSrc";
nu = 1.0; prm.find("nu", nu);
prob = 1; prm.find("problem", prob);
if (prob == 3)
{
...
this->calcFourierCoefficient(accuracy);
}
}
BurgersMSrc::~BurgersMSrc(){}
inline void BurgersMSrc::getValues (Vector &coords, Vector &msrc)
{
...
}
void BurgersMSrc::calcFourierCoefficient(int p)
{
for(int n=0;n<specModes;n++)
{
if (time == 0)
{
a_re[n] = randomNumber(p);
a_im[n] = randomNumber(p);
}
else
{
a_re[n] = a_re[n]*exp(-tT) + randomNumber(p);
a_im[n] = a_im[n]*exp(-tT) + randomNumber(p);
}
}
}
double BurgersMSrc::randomNumber(int p)
{
int mod = pow(10,p);
int rN = -mod + rand() % (2*mod);
randomNr = rN/(double)mod;
return randomNr;
}
主程序的相關線路:
#include "mfem.hpp"
#include "mex.h"
#include "BurgersMSS.h"
...
int main (int argc, char *argv[]) {
...
ValSrc *srcTerm;
...
if (problem==1) {
... srcTerm = new ConstVS(f);
...
} else if (problem==2) {
... srcTerm = new ConstVS(f);
...
} else if (problem==3){
srcTerm = new BurgersMSrc(prm);
...
} else {
srcTerm = new BurgersMSrc(prm);
...
}
...
stiffInt->setSrc(*srcTerm);
...
for (int step = 0; step < nTimeSteps; step ++) {
...
if (problem == 3)
{
srcTerm->calcFourierCoefficient(accuracy); //This line throws the error
}
...
}
...
return 0;
}
我不是很瞭解這方面的知識,但看看使用動態演員表。如果你嘗試動態地將基類轉換爲派生類,它應該拋出一個異常 – Vlad