代码没有编译

时间:2010-04-27 13:04:41

标签: 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;
}

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

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

编译时出现以下错误:

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

4 个答案:

答案 0 :(得分:6)

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

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

将该功能标记为模板功能

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

编译器会很开心。 并将函数定义放在类定义之前。

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> &);
};

答案 1 :(得分:2)

我认为链接器找不到你的功能。将所有代码放在头文件中。

答案 2 :(得分:0)

它正在编译,它只是没有链接。 (我知道,这不是一个很大的帮助。)你没有一个实例化功能模板的地方。你有一个试图使用这个流插入操作符的main()吗?

答案 3 :(得分:0)

[剪断]

以下适用于使用Visual Studio 2005的Windows

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;
}
相关问题