[英]Call a derived class' (non-virtual) function in the base class' Destructor
[英]Why won't derived class access a non-virtual base class function?
我无法使派生类访问基类中定义的函数。 基类头文件名为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;
}
派生类头文件名为Star.h,它是:
#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 ++项目中成功地从派生类调用了基类函数,所以我必须在这里忽略一些简单的东西,但我找不到它。 我认为基类函数应该由派生类继承,除非它们被声明为虚拟然后在派生类中重写(但这不是这里的情况),即使派生类重载函数名称,因为我在这里做了一对时间。 这不是真的吗? 如果没有,我可以做些什么来解决这个问题,而不仅仅是在我的派生类中重新定义相同的函数?
非常感谢您的帮助。
你必须using getX;
添加using getX;
在派生类中,或在函数中使用particle::getX
。
标准表示如果派生函数具有相同名称的函数,则不会自动使用基类函数 - 即使派生函数不适合。 这是为了防止错误。
你必须告诉派生类它将使用基类'函数(通过using getX;
direvtive)或显式调用基类'函数(通过调用particle::getX(...)
)
基类中函数getX的声明是:
virtual vector<double> getX(const double theta, double Real phi);
但定义是:
vector<double> Particle::getX(const unsigned int surfindex)
{
//Stuff
}
签名不符! 更改声明 ,代码将工作
BTW一个矢量的副本非常昂贵,请考虑使用参考文献更改您的设计
答案是:如果基类具有'n'个函数的重载版本,并且在派生类中重新定义/覆盖(更改正文)或重载(更改签名)该函数,那么只有该版本派生类可供您使用。
样品:
class Base
{
public:
int abc(){}
float abc(){}
};
class Der:public Base
{
public:
SomeClassObj abc(){} //int and float returning versions of abc are now hidden for Der object
};
覆盖/重新定义的情况也是如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.