从派生的模板类调用函数 [英] Calling a function from a derived template class

查看:150
本文介绍了从派生的模板类调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的基类:

//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


未定义的符号:
Element ::加(元素const&),引用自:
vtable for Vectorin main.o

Element :: Element(),引用自:
在main.o中的Vector :: Vector()

在main.o中的Vector :: Vector(double const&,double const&,double const&)

Element :: minus (元素const&),引自:
vtable for Vectorin main.o

typeinfo for Element,引用自:
typeinfo for Vectorin main .o

ld:未找到符号

collect2:ld返回1退出状态

Undefined symbols: "Element::plus(Element const&)", referenced from:
vtable for Vectorin main.o
"Element::Element()", referenced from:
Vector::Vector()in main.o
Vector::Vector(double const&, double const&, double const&)in main.o
"Element::minus(Element const&)", referenced from:
vtable for Vectorin main.o
"typeinfo for Element", referenced from:
typeinfo for Vectorin main.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

这是因为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.

这篇关于从派生的模板类调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆