[英]C++ - Error when using class template
In file main.cpp... 在文件main.cpp中...
#include "pqueue.h"
struct nodeT;
struct coordT {
double x, y;
};
struct arcT {
nodeT *start, *end;
double weight;
};
int arcComp(arcT *arg0, arcT *arg1){
if(arg0->weight == arg1->weight)
return 0;
else if(arg0->weight > arg1->weight)
return 1;
return -1;
}
struct nodeT {
coordT* coordinates;
PQueue<arcT *> outgoing_arcs(arcComp); // error on this line
};
In file pqueue.h ... 在文件pqueue.h中...
#ifndef _pqueue_h
#define _pqueue_h
template <typename ElemType>
class PQueue
{
private:
typedef int (*CallbackFunc)(ElemType, ElemType);
CallbackFunc CmpFunc;
public:
PQueue(CallbackFunc Cmp);
~PQueue();
};
#include "pqueue.cpp"
#endif
In file pqueue.cpp 在文件pqueue.cpp中
#include "pqueue.h"
template <typename ElemType>
PQueue<ElemType>::PQueue(CallbackFunc Cmp = OperatorCmp)
{
CmpFunc = Cmp;
}
template<typename ElemType>
PQueue<ElemType>::~PQueue()
{
}
error C2061: syntax error : identifier
'arcComp'
错误C2061:语法错误:标识符
'arcComp'
The syntax is simply invalid, you cannot initialise members in-place; 语法完全无效,您不能就地初始化成员。 use a constructor.
使用构造函数。
struct nodeT {
coordT* coordinates;
PQueue<arcT *> outgoing_arcs;
nodeT() : ougoing_arcs(arcComp) { }
};
Apart from that you cannot (usually) define templates in cpp files, you must put the complete definition inside the header file. 除了不能(通常)在cpp文件中定义模板之外,还必须将完整的定义放在头文件中。 Granted, you are
#include
ing the cpp file rather than treating it as a separate compilation unit but that's still bad, if only because it will trip up programmers' expectations and automated build tools. 当然,您正在
#include
cpp文件,而不是将其视为单独的编译单元,但这仍然很糟糕,即使仅仅是因为它将破坏程序员的期望和自动化的构建工具。
As a final side-note, your code is violating every single C++ naming convention I have ever encountered. 最后一点,您的代码违反了我所遇到的每一个C ++命名约定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.