【发布时间】:2020-08-02 02:28:19
【问题描述】:
我遇到了这个错误,我无法完全理解为什么会发生。我正在尝试在基类中使用模板函数:
在 .h 文件中
class CylindricalWave {
public:
virtual ~CylindricalWave() {}
virtual double intensity(double r, double z, double t) = 0;
virtual std::complex<double> efield(double r, double z, double t) = 0;
template<int Nr, int Nz>
Eigen::Matrix<std::complex<double>, Nz, Nr> efield(Eigen::Matrix<double, Nz, Nr>& rs, Eigen::Matrix<double, Nz, Nr>& zs, double t);
template<int Nr, int Nz>
Eigen::Matrix<std::complex<double>, Nz, Nr> intensity(Eigen::Matrix<double, Nz, Nr>& rs, Eigen::Matrix<double, Nz, Nr>& zs, double t);
};
我也在 .h 文件中定义了我的模板方法:
template<int Nr, int Nz>
Eigen::Matrix<std::complex<double>, Nz, Nr> CylindricalWave::efield(Eigen::Matrix<double, Nz, Nr>& rs, Eigen::Matrix<double, Nz, Nr>& zs, double t) {
Eigen::Matrix<std::complex<double>, Nz, Nr> output;
for (size_t i = 0, size = rs.size(); i < size; i++)
{
double temporary_r = (*(rs.data() + i));
double temporary_z = (*(zs.data() + i));
*(output.data()+i) = this->efield(temporary_r, temporary_z, t); //here I call the virtual efield of Cylindrical Wave. I thought the compiler would understand that it has to call the child method that accepts doubles.
}
return output;
}
现在我有一个名为 GaussianBeam 的子类,我在其中覆盖了 efield 方法:
class GaussianBeam : public CylindricalWave {
public:
virtual std::complex<double> efield(double r, double z, double t); //this is the define this virtual method.
virtual double intensity(double r, double z, double t); //I also define this one.
};
现在定义了 efield(接受 double r, double z, double t 的版本),我希望我的 efield 模板版本允许我调用:
GaussianBeam gauss = GaussianBeam();
const int Nx = 3;
const int Ny = 2;
//creates the "meshgrid"
Eigen::Matrix<double, Ny, Nx> X = Eigen::RowVectorXd::LinSpaced(Nx, -5e-4,5e-4).replicate(Ny,1);
Eigen::Matrix<double, Ny, Nx> Y = Eigen::VectorXd::LinSpaced(Ny, -5e-3, 5e-3).replicate(1, Nx);
//calculates the field:
//I would have expected the code to call the parent version of efield since it's the only that matched the signature of the arguments. Yet, I feel like it's trying to call the one that uses doubles that was defined in the class GaussianBeam.
gauss.efield<Nx, Ny>(X, Y, 0);
但最后一行只是说Invalid use of member function (did you forget the ‘()’ ?),我不太明白,因为我认为 GaussianBeam 会继承 efield 的模板版本,我可以从 GaussianBeam 的实例中调用它。
为什么会这样?我对继承有什么误解?谢谢。
【问题讨论】:
-
gauss是什么?此名称从未在所示代码中声明。 -
抱歉,我的问题打错了。现在已修复。
gauss是 GaussianBeam 的一个实例。
标签: c++ templates inheritance