我無法讓派生類訪問在基類中定義的函數。基類的頭文件,稱爲Particle.h,是:爲什麼派生類不能訪問非虛擬基類函數?
class Particle {
protected:
vector<double> x_,y_,z_;
// lots of other protected members that are not relevant to the question
public:
// constructors and other functions not relevant to question are omitted
virtual double getX(const unsigned int index, const double theta, const double phi);
virtual vector<double> getX(const double theta, double Real phi);
vector<double> getX(const unsigned int surfindex);
}
此函數的定義是在一個稱爲Particle.cc文件:
#include "Particle.h"
vector<double> Particle::getX(const unsigned int surfindex)
{
vector<double> xp;
xp.clear();
xp.resize(3,0.0);
xp[0] = x_.at(surfindex);
xp[1] = y_.at(surfindex);
xp[2] = z_.at(surfindex);
return xp;
}
派生類的頭文件,稱爲星。小時,是:
#include "Particle.h"
using namespace std;
class Star : public Particle {
public:
// constructors and other functions not relevant to question are omitted here
virtual void computeRoundness(const unsigned int method);
double getX(const unsigned int index, const double theta, const double phi);
vector<double> getX(const double theta, double Real phi);
}
的computeRoundness函數的定義是在一個稱爲Star.cc文件:
#include "Star.h"
// Lots of other function definitions not relevant to question are omitted here
void Star::computeRoundness(const unsigned int method)
{
vector<double> X;
unsigned int count = 0;
while (count < ntheta) {
X = getX(count); // Should call base class function, right?
// do some more things with X that are not relevant to this question
}
}
但我收到此編譯時錯誤:
Star.cc: In member function ‘virtual void Star::computeRoundness(unsigned int)’:
Star.cc:1340: error: no matching function for call to ‘Star::getX(unsigned int&)’
Star.h:687: note: candidates are: virtual double Star::getX(unsigned int, double, double)
Star.h:696: note: virtual std::vector<double, std::allocator<double> > Star::getX(double, double)
我在其他C++在過去的項目已經成功地被稱爲從派生類的基類的功能,所以我必須在這裏可以俯瞰簡單的東西,但我只是找不到它。我認爲基類函數應該被派生類繼承,除非它們被聲明爲虛擬的,然後在派生類中被重寫(但這不是這種情況),即使派生類重載函數名稱,因爲我已經在這裏完成了一對的時代。這不正確嗎?如果沒有,我能做些什麼來解決這個問題,而不是僅僅在派生類中重新定義相同的函數呢?
非常感謝您的幫助。
[函數具有相同名稱但派生類中籤名不同](http://stackoverflow.com/questions/411103/function-with-same-name-but-different-signature-in-derived-class ) –
我喜歡[我以前的答案](http://stackoverflow.com/a/6035884/8747)到一個類似的問題。 –