Domanda

I am working on a stack class and have two constructors. One of interest is this one.

template <typename T>
stack<T>::stack( const int n)
{
 capacity = n ;
 size = 0 ;
 arr = new T [capacity] ;
}

I am calling it inside main like this.

stack<int> s1(3) ;

The program compiles fine but i get this run time error.

1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall
 stack<int>::~stack<int>(void)" (??1?$stack@H@@QAE@XZ) referenced in function _main

1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall    
stack<int>::stack<int>(int)" (??0?$stack@H@@QAE@H@Z) referenced in function _main

1>D:\\Microsoft Visual Studio 10.0\Visual Studio 2010\Projects\Expression
 Evaluation\Debug\Expression Evaluation.exe : fatal error LNK1120: 2 unresolved externals

I am working on Microsoft visual studio 2010 and this problem is taking me nowhere. Any hint would be appreciated.

È stato utile?

Soluzione

It's not a runtime error, it's a linker error. The problem is probably that the implementations of the constructor and the destructor are in a source file. With template classes, you have to place the implementations of all the methods in the header (or in the source file that uses them, but that's equivalent to putting them in the header).

So basically do this:

template<class T>
class stack
{
public:
    stack( const int n)
    {
        capacity = n ;
        size = 0 ;
        arr = new T [capacity] ;
    }

    // and the same for all other method implementations
};
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top