c++ - 如何使用虚函数返回指向基类的指针?

标签 c++ inheritance templates virtual return

我有一个名为 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/

相关文章:

c++ - stringstream 的第一个字符串参数被保存为指针/垃圾

c++ - 在 C++ 中创建 RGBA 图像

c++ - 使用纯虚拟成员地址的虚拟调用。合法吗?

c++ - 为什么编译器不能从函数参数中推断出我的模板值?

wpf - 如何为我的 Wpf UserControl 实现 DisplayMemberPath?

c++ - 在 C++ 中为字符串指针的动态数组寻找一个简单的包装器

c++ - 如何让类(class)更有凝聚力?

python - 在 __add__ 运算符中返回相同子类的对象

c++ - 如何显式实例化基本模板类?

c++ - 两个具有相同大小的可变模板参数