如何使用指向模板类型的指针
对于这个问题的初学者性质,我深表歉意。我似乎无法获得指向模板类型的指针来工作。例如,这是一个头文件:
#include "TemplatedClass.h"
using namespace std;
class PointList
{
public:
PointList(TemplatedClass<Point> *p);
//snip
};
这似乎不合法。我做错了什么?谢谢!
编辑添加到示例中。
//TemplatedClass.h
template <class T>
class TemplatedClass
{
public:
TemplatedClass();
TemplatedClass(T *t);
TemplatedClass(const TemplatedClass &t);
~TemplatedClass();
T *getNode() const;
void setNode(T *t);
private:
T *node;
};
//TemplatedClass.cpp
#include "TemplatedClass.h"
template <class T>
TemplatedClass<T>::TemplatedClass()
{
node = 0;
};
template <class T>
TemplatedClass<T>::TemplatedClass(T *t)
{
node = t;
};
template <class T>
TemplatedClass<T>::TemplatedClass(const TemplatedClass &l)
{
// snip
};
I apologize for the beginner nature of this question. I can't seem to get a pointer to a templated type to work. For example, here is a header file:
#include "TemplatedClass.h"
using namespace std;
class PointList
{
public:
PointList(TemplatedClass<Point> *p);
//snip
};
This doesn't seem to be legal. What have I done wrong? Thanks!
edit adding to example.
//TemplatedClass.h
template <class T>
class TemplatedClass
{
public:
TemplatedClass();
TemplatedClass(T *t);
TemplatedClass(const TemplatedClass &t);
~TemplatedClass();
T *getNode() const;
void setNode(T *t);
private:
T *node;
};
//TemplatedClass.cpp
#include "TemplatedClass.h"
template <class T>
TemplatedClass<T>::TemplatedClass()
{
node = 0;
};
template <class T>
TemplatedClass<T>::TemplatedClass(T *t)
{
node = t;
};
template <class T>
TemplatedClass<T>::TemplatedClass(const TemplatedClass &l)
{
// snip
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要通过包含定义该类的标头来提供 Point 类的定义。例如:
编辑
实际上,由于您的方法需要一个指针,因此您可以只转发声明:
但是然后在源(cpp)文件中您需要包含这些标头
You need to provide the definition of the Point class by including a header where that class is defined. For example :
EDIT
Actually, since your method takes a pointer, you can just forward declare :
but then in the source (cpp) file you need to include those headers
尝试将所有成员函数模板定义从 TemplatedClass.cpp 移至 TemplateClass.hh。所有模板定义都应位于头文件中(简化)。
Try to move all the member function template definitions from TemplatedClass.cpp to TemplateClass.hh. All the template definitions should be in header files (simplified).