C++ - 使用类模板时出错

标签 c++ class-template

在文件 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/

相关文章:

c++ - 是否有按值传递类对象的标准程序?

c++ - 提升 : having an array of ints and some special int how to find nearest to yours in array?

c++ - 模板类的模板成员函数特化,无需指定类模板参数

c++ - 如何在运算符重载中将int类型的模板矩阵类静态转换为double类型?

c++ - 如何修复 'No matching function for call to ' strtok''

c++ - Ping 网络并获取 mac 地址

c++ - 在 Ctrl+Z (EOF) 后恢复从 iostream::cin 读取? ("ignore"不起作用)

c++ - 如何在派生类中初始化基类静态内联数据成员?

c++ - Clion c++ 中友元函数的错误

c++ - 模板函数和类