在文件 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
};
在文件 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
在文件 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'
最佳答案
语法完全无效,您不能就地初始化成员;使用构造函数。
struct nodeT {
coordT* coordinates;
PQueue<arcT *> outgoing_arcs;
nodeT() : ougoing_arcs(arcComp) { }
};
除此之外,您不能(通常)在 cpp 文件中定义模板,您必须将完整的定义放在头文件中。诚然,您正在 #include
处理 cpp 文件,而不是将其视为单独的编译单元,但这仍然很糟糕,因为它会破坏程序员的期望和自动构建工具。
作为最后的旁注,您的代码违反了我遇到过的每一个 C++ 命名约定。
关于C++ - 使用类模板时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7769426/