开发者

Undefined reference to template members

开发者 https://www.devze.com 2023-01-23 19:27 出处:网络
I\'m new to C++, and preparing a homework by using NetBeans IDE on Ubuntu 10.04. I use g++ as a C++ compiler.

I'm new to C++, and preparing a homework by using NetBeans IDE on Ubuntu 10.04. I use g++ as a C++ compiler.

The error message:

build/Debug/GNU-Linux-x86/Maze.o: In function `Maze':
Maze/Maze.cpp:14: undefined reference to `Stack<Coordinate>::Stack()'
Maze/Maze.cpp:14: undefined reference to `Stack<Coordinate>::Stack()'
Maze/Maze.cpp:69: undefined reference to `Stack<Coordinate>::push(Coordinate)'
Maze/Maze.cpp:79: undefined reference to `Stack<Coordinate>::isEmpty()'
Maze/Maze.cpp:87: undefined reference to `Stack<Coordinate>::destroy()'

And my related code:

Maze.h

#include "Coordinate.h"
#include "Stack.h"
....
....
/**
 * Contains the stack object
 *
 * @var  Stack stack
 * @access private
 */
Stack<Coordinate> *stack;
...
...

Maze.cpp

#include "Maze.h"
...
...
Maze::Maze()
{
    // IT SHOWS THAT THE FOLLOWING LINE HAS AN ERROR///
    stack = new Stack<Coordinate>;
    ///////////////////////////////////////////////////

    for( int y=0; y<8; y++ )
    {
开发者_如何学Python        for( int x=0; x<8; x++ )
        {
            maze[y][x] = '0';
        }
    }
}
...
...

And according to the error output, Each line that I used stack variable has an error: Undefined reference.

Stack.cpp

#include "Stack.h"
...
...
template <class T> Stack<T>::Stack()
{
    // Create the stac!
    create();
}
...

I have googled it, but could not solve the problem. I think there is something wrong with my includes order, or maybe I used the pointers in a wrong way.

I also tried to create a makefile by myself, but the result did not change. I prepared this makefile according to this link: http://www.cs.umd.edu/class/spring2002/cmsc214/Tutorial/makefile.html

Here is my makefile:

maze: Maze.o Stack.o Coordinate.o
 g++ -Wall Maze.o Stack.o Coordinate.o -o maze

Maze.o: Maze.cpp Maze.h Stack.h Coordinate.h
 g++ -Wall -c Maze.cpp

Stack.o: Stack.cpp Stack.h
 g++ -Wall -c Stack.cpp

Coordinate.o: Coordinate.cpp Coordinate.h
 g++ -Wall -c Coordinate.cpp

Maze.h: Stack.h Coordinate.h

How could I overcome this error? Any ideas?


Stack is a template. The complete definition has to go in its header file. That is, do not separate it into a .h and a .cpp file.

0

精彩评论

暂无评论...
验证码 换一张
取 消