我有一个名为 Element 的基类和一个名为 Vector 的派生类,我试图在 Vector 中从 Element 重新定义两个虚函数。
//element.h
template <class T>
class Element
{
public:
Element();
virtual Element& plus(const Element&);
virtual Element& minus(const Element&);
};
在另一个文件中
//Vector.h
#include "Element.h"
template <class T>
class Vector: public Element<T> {
T x, y, z;
public:
//constructors
Vector();
Vector(const T& x, const T& y = 0, const T& z =0);
Vector(const Vector& u);
...
//operations
Element<T>& plus(const Element<T>& v) const;
Element<T>& minus(const Element<T>& v) const;
...
};
//sum
template <class T>
Element<T>& Vector<T>::plus(const Element<T>& v) const
{
Element<T>* ret = new Vector((x + v.x), (y + v.y), (z + v.z));
return *ret;
}
//difference
template <class T>
Element<T>& Vector<T>::minus(const Element<T>& v) const
{
Vector<T>* ret = new Vector((x - v.x), (y - v.y), (z - v.z));
return *ret;
}
但我总是得到
error: 'const class Element' has no member named 'x'
那么,我是否可以定义我的虚函数来将 Vector& 作为参数,或者我是否可以通过指向 Element 的指针访问 Vector 的数据成员?
我对继承多态性还很陌生,仅供引用。
编辑:尝试 static_cast(如下所示)并没有解决我的问题——或者我的语法错误。我已经用我能想到的两种方式尝试了静态转换,现在我的错误是 > error: 'const class Element' has no member named 'x'
我更新的代码是: //和 模板 元素和 vector::加(常量元素和 v)常量 { 元素* ret = static_cast*>(运算符新((x + v.x), (y + v.y), (z + v.z))); 返回 *ret; }
//difference
template <class T>
Element<T>& Vector<T>::minus(const Element<T>& v) const
{
Element<T>* ret = new Vector<T>(static_cast<Vector*>((x - v.x), (y - v.y), (z - v.z)));
return *ret;
}
我认为继承多态性的全部意义在于对派生类的引用实际上与对基类的引用相同。为什么我必须跳过这些障碍?
最佳答案
编译器说的很明显:基类 Element 没有 具有成员变量“x”,因为 x 是在 Vector 中而不是在 Element 中声明的。 试试这个:
Element<T>& plus(const Element<T>& v) const {
const Vector<T> & vect = dynamic_cast<const Vector<T> &>(v);
Vector<T>* ret = new Vector((x + vect.x), (y + vect.y), (z + vect.z));
return *ret;
}
请注意,如果您以这种方式返回一个指针,您可能会遇到任何内存泄漏问题。
关于c++ - 如何使用虚函数返回指向基类的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3058820/