Domanda

I am developing C++ on Netbeans 7.1 on Ubuntu 11.04. I was wondering if someone could tell me why Stack fs(5); is seen as an undefined reference to to `Stack::Stack(int)'. Why is it not seen as a class with float used for T?

#include <iostream>

using namespace std ;

template <class T>
class Stack
{
public:
    Stack(int = 10) ;
    ~Stack() { delete [] stackPtr ; }
    int method1(const T&); 
    int method2(T&) ;  
    int method3()const { return top == -1 ; }
    int method4() const { return top == size - 1 ; }
private:
    int attribute1 ;  
    int attribute2 ;
    T* stackPtr ;
} ;


using namespace std; 
int main()
{
    // This line gives the error message "undefined reference to `Stack<float>::Stack(int)'"
    Stack<float> fs(5);

    return 0;
}

Thanks, Peter.

È stato utile?

Soluzione

I don't see the actual code for Stack<float>::Stack(int) anywhere. You've declared it, but there's no definition. So it doesn't actually exist (even though you're saying it does; the compiler often just takes your word for it), and the linker won't be able to find it, if it even gets that far.

You need to either define the function similarly to how you've defined ~Stack(), or have it elsewhere in the code the same way you'd have any other member function.

Altri suggerimenti

To use class template, you must define them, only declaration is not enough. What the compiler does is when is find a real usage of class template, say Stack<int>, it put int to replace T in your class template definition and generate a class for it. When it sees Stack<double>, it generates a another type base on your class template, these generated types are called template class.

By the way, How can I use the c++ grammar<"int">(ignore ") int the reply, it just disappear.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top