代码没有编译

Sur*_*uri 0 c++ linker-errors

//cstack.h
# ifndef _STACK_H__
#define _STACK_H__

#include<iostream>
#include<vector>

template< class Type ,int Size = 3>
class cStack
{
 Type *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;
}
Run Code Online (Sandbox Code Playgroud)

 

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

int main()
{
 cStack<int> sobj(1);
 std::cout << sobj;
}
Run Code Online (Sandbox Code Playgroud)

当我编译时,我收到以下错误:

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
Run Code Online (Sandbox Code Playgroud)

Tim*_*imW 6

35.16 使用模板朋友时为什么会出现链接器错误?

friend std::ostream& operator<< (std::ostream &, const cStack<Type, Size> &);
Run Code Online (Sandbox Code Playgroud)

将该功能标记为模板功能

friend std::ostream& operator<< <>(std::ostream &, const cStack<Type, Size> &);
Run Code Online (Sandbox Code Playgroud)

编译器会很高兴.并将函数定义放在类定义之前.

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> &);
};
Run Code Online (Sandbox Code Playgroud)

  • 更多信息:http://www.parashift.com/c++-faq-lite/templates.html#faq-35.16(我宁愿在最后提出建议.) (2认同)