gpt4 book ai didi

c++ - 为什么派生类不能访问非虚拟基类函数?

转载 作者:太空狗 更新时间:2023-10-29 20:26:39 25 4
gpt4 key购买 nike

我无法让派生类访问基类中定义的函数。名为 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;,或者在函数中使用 particle::getX

标准规定,如果派生类具有同名函数,您不会自动使用基类的函数——即使派生类的函数不适合。这是为了防止错误。

您必须告诉派生类它将使用基类的函数(通过 using getX; 指令)或显式调用基类的函数(通过调用 particle::getX(...))

关于c++ - 为什么派生类不能访问非虚拟基类函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19038568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com