开发者

code is not compiling

//cstack.h
# ifndef _STACK_H__
#define _STACK_H__

#include<iostream>
#include<vector>

template< class Type ,int Size = 3>
class cStack
{
 Typ开发者_Python百科e *m_array;
 int m_Top;
 int m_Size;

public:
    cStack();
    cStack(const Type&);
    cStack(const cStack<Type,Size> &);
    int GetTop()const;
    bool Is_Full()const;
    bool Is_Empty()const;
    void InsertValue(const Type&);
    void RemeoveValue();
    void show();  
    ~cStack();
    friend std::ostream& operator <<(std::ostream &, const cStack<Type,Size> &);
};

// iam writing only one function defination because linking is because of this function
template< class Type,int Size >
std::ostream& operator << ( std::ostream &os, const cStack<Type,Size> &s)
{
 for( int i=0; i<=s.GetTop();i++)
 {
  os << s.m_array[i];
 }
 return os;
}

 

//main.cpp
#include "cStack.h"
#include <string>
#include<iostream>

int main()
{
 cStack<int> sobj(1);
 std::cout << sobj;
}

When I compile I get the following error:

error LNK2019: unresolved external symbol "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class cStack<int,3> const &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABV?$cStack@H$02@@@Z) referenced in function _main


35.16 Why do I get linker errors when I use template friends?

friend std::ostream& operator<< (std::ostream &, const cStack<Type, Size> &);

Mark the function as template functions

friend std::ostream& operator<< <>(std::ostream &, const cStack<Type, Size> &);

And the compiler will be happy. And put the function definition before the class definition.

template< class Type ,int Size>
class cStack;

template< class Type ,int Size >
std::ostream& operator <<(std::ostream &os, const cStack<Type,Size> &s)
{
    for( int i=0; i<=s.GetTop();i++)
    {
        os << s.m_array[i];
    }
    return os;
}


template< class Type ,int Size = 3>
class cStack
{
    Type *m_array;
    int m_Top;
    int m_Size;
public:
    cStack() {}
     //...
    friend std::ostream& operator<< <>(std::ostream &, const cStack<Type, Size> &);
};


I think the linker can't find your function. Place all the code in the the header file.


It's compiling, it's just not linking. (I know, that's not a big help.) You don't have a place where the function template is being instantiated. Do you have a main() somewhere that tries to use this stream insertion operator?


[snip]

The following works on windows with Visual Studio 2005

template <class Type, int Size = 3 >
class cStack 
{
    // ....

    template<class Type>
    friend std::ostream& operator<< (std::ostream & os, const cStack<Type> &s);
};

template<class Type>
std::ostream& operator << (std::ostream &os, const cStack<Type> &s)
{
    for( int i=0; i < s.GetTop();i++)
    {
        os << s.m_array[i];
    }
    return os;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜