When I attempt to insert this 'food' object into my template class linked list 'test'. I get this error:
request for member ‘开发者_运维技巧addNode’ in ‘test’, which is of non-class type ‘Catalog<FoodSource>()
Here's my coding, What am I doing wrong?
##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);
}
}
You just found one of the many warts present in the C++ syntax. The standard requires that if an expression can be interpreted both as a declaration and as a definition then it must be considered as a declaration. For example your code
Catalog<FoodSource> test();
is not defining a variable named test
but is instead declaring that there is a function named test that takes no arguments and that returns a Catalog<FoodSource>
instance.
To define the variable you need to omit the parenthesis.
Note that there are cases where this trap is much harder to notice... for example:
double x = 3.14159;
int y(int(x));
as surprising it may seem in the above code y
is declared as a function!
Declaration and implementation of a class template should be in the same file.
Also, you can just call test.addNode(food);
in main
.
Given definition for all the classes Node, FoodSource etc is available, you need to do at least the following:
1) Move the function definition to .h file
2) The first line in main function is ambigous. It should be rewritten as Catalog<FoodSource> test;
because Catalog<FoodSource> test()
will be treated as function prototype
精彩评论