gpt4 book ai didi

c++ - 代码未编译

转载 作者:太空宇宙 更新时间:2023-11-04 15:10:28 25 4
gpt4 key购买 nike

//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

最佳答案

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

关于c++ - 代码未编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2721381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com