2011-05-03 45 views
0

当我试图插入这个'食物'对象到我的模板类链接列表'测试'。我得到这个错误:模板类链接列表插入错误

request for member ‘addNode’ in ‘test’, which is of non-class type ‘Catalog<FoodSource>() 

这是我的编码,我做错了什么?

##main:## 

int main(void) 
{ 
    Catalog<FoodSource> test(); 
    FoodSource food(); 
    test.addNode(const &food); 
    return(0); 
} 

##function definition in .h:## 

template<class T> 
class Catalog 
{ 
    public: 
     void addNode(const T& value); 
}; 

##function implementation in .cpp:## 

template <class T> 
void Catalog<T>::addNode(const T& value) 
{ 
    Node *temp; 

    if(head == NULL) 
     head = new Node (value, NULL); 
    else 
    { 
     temp=head; 

     while(temp->next !=NULL) 
      temp=temp->next; 

     temp->next = new Node (value, NULL); 
    } 
} 

回答

4

您刚发现C++语法中存在的许多疣中的一个。该标准要求,如果表达式既可以被解释为声明又可以被解释为定义,那么它必须被视为声明。例如你的代码

Catalog<FoodSource> test(); 

没有定义一个名为test变量而是宣称有一个功能名为test,它没有参数和返回Catalog<FoodSource>实例。

要定义变量,您需要省略括号。

注意,存在以下情况:这个陷阱更难看到...例如:

double x = 3.14159; 
int y(int(x)); 

为惊人的它可能看起来在上面的代码yis declared as a function

+1

aka [最令人头疼的解析](http://en.wikipedia.org/wiki/Most_vexing_parse)。 – 2011-05-03 07:06:38

+0

感谢您的链接。有效的STL正是我了解这个可怕的陷阱的地方......我决定永远不会浪费时间编写C++解析器。 – 6502 2011-05-03 08:49:46

0

声明和实施类模板应该是in the same file

此外,您可以拨打main致电test.addNode(food);

+0

.h文件包含在.cpp中。调用test.addNode(食物);给我同样的错误。 – 2011-05-03 06:56:04

+0

@迈克尔:有了模板,这是不够的。编译器在实例化时需要完整的模板定义(在'main'中就是这种情况)。 – 2011-05-03 07:07:30

0

所有类节点鉴于定义,FoodSource等是可用的,你至少需要做到以下几点:

1)将函数定义.h文件中

2)第一行中主要功能是ambigous。它应该被重写为Catalog<FoodSource> test;,因为Catalog<FoodSource> test()将被视为函数原型