【问题标题】:C++ - Error when using class templateC++ - 使用类模板时出错
【发布时间】:2011-10-14 14:51:34
【问题描述】:

在文件 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()
{
}

错误 C2061:语法错误:标识符 'arcComp'

【问题讨论】:

  • 所以..........?编译器告诉你出了什么问题,它不明白这一行:PQueue&lt;arcT *&gt; outgoing_arcs(arcComp); - 有什么问题?
  • 问题是“为什么”?为什么编译器不理解那行?
  • 为什么要包含 pqueue.cpp?
  • 该行应该定义成员函数还是变量,因为编译器将其视为第一个。
  • @SegFault - 答案取决于你想要做什么 - 显然编译器没有理解它 - 你是在声明数据成员还是成员函数?如果是前者 - 请参阅 Konrad 的回答,如果是后者,则说明您没有正确声明...

标签: c++ class-template


【解决方案1】:

语法完全无效,您不能就地初始化成员;使用构造函数。

struct nodeT {
    coordT* coordinates;
    PQueue<arcT *> outgoing_arcs;

    nodeT() : ougoing_arcs(arcComp) { }
};

除了你不能(通常)在 cpp 文件中定义模板之外,你必须将完整的定义放在头文件中。诚然,您是 #includeing cpp 文件,而不是将其视为一个单独的编译单元,但这仍然很糟糕,因为它会破坏程序员的期望和自动化构建工具。

作为最后的旁注,您的代码违反了我遇到的每一个 C++ 命名约定。

【讨论】:

  • “你不能(通常)在 cpp 文件中定义模板”,我这样做是为了将接口与实现分开,我想这是件好事
  • @SegFault:你可以试试“.ipp”而不是“.cpp”:stackoverflow.com/questions/543507/…
  • @SegFault 是的。但是不要调用实现文件pqueue.cpp.cpp 专门保留对应编译单元!要么使用扩展名 .ipp,这已经成为一种惯例,要么使用明确的 .impl.hpp.impl.h 或类似名称。
  • 你能解释一下“nodeT() : ougoing_arcs(arcComp) { }”实际上在做什么吗?
  • @SegFault C++ 中的类和结构几乎没有区别。唯一的区别是默认情况下,结构中的所有内容都是公共的,而在类中它是私有的。就是这样。
猜你喜欢
  • 2023-03-24
  • 2021-12-27
  • 1970-01-01
  • 2016-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-11
相关资源
最近更新 更多