问题描述
我的基类:
//Element.h
class Element
{
public:
Element();
virtual ~Element(){}; // not sure if I need this
virtual Element& plus(const Element&);
virtual Element& minus(const Element&);
};
派生模板类:
//Vector.h
#include "Element.h"
template <class T>
class Vector: public Element {
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& plus(const Element&) const;
Element& minus(const Element&) const;
...
};
...
//summation
template <class T>
Element& Vector<T>::plus(const Element& v) const
{
const Vector<T>& w = static_cast<const Vector<T>&>(v);
Vector<T>* ret = new Vector<T>((x + w.x), (y + w.y), (z + w.z));
return *ret;
}
//difference
template <class T>
Element& Vector<T>::minus(const Element& v) const
{
const Vector<T>& w = static_cast<const Vector<T>&>(v);
Vector<T>* ret = new Vector<T>((x - w.x), (y - w.y), (z - w.z));
return *ret;
}
我在此代码中遇到了另一个问题(在),但目前我正在努力解决这样一个事实:如果我试图运行它,我得到
I had another issue with this code (answered in another post), but currently I'm wrestling with the fact that if I try to run this, I get
这是因为e派生的模板类不与基类放在同一个文件中,这会导致编译器问题(类似于我在头文件中定义整个Vector类的方式)?
Is this because the derived template class isn't housed in the same file as the base class, and that's causing compiler issues (similar to how I had to define the entire Vector class in the header file)?
我对C ++很新,还在阅读vtable是什么以及它们是如何工作的,但是我还不能理解这一点。
I'm fairly new to C++, and still reading up on what vtables are and how they work, but I can't quite figure this out yet.
推荐答案
我认为编译器/链接器在它告诉你未定义的符号时意味着它:Element :: plus(Element const&)
。这些符号(元素的加号和减号)已经声明,但尚未定义。
I think the compiler/linker means it when it tells you Undefined symbols: "Element::plus(Element const&)"
. These symbols (plus and minus for Element) have been declared but they have not been defined.
这篇关于从派生的模板类调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!