重载<<的问题

csproj 2009-10-07 03:51:57
编译错误,无法解析的外部命令。
找了半天,没找到错误,麻烦帮忙看一下。

#include "iostream"
using namespace std;

template<class T>
class C1
{
friend ostream& operator<<(ostream&,const C1<T>&);
public:
C1(){value = 999;}
private:
int value;
};

//重载<<
template<class T>
ostream& operator<<(ostream& out,const C1<T>& c)
{
out << c.value;
return out;
}

//换成下面的函数能正常工作
//ostream& operator<<(ostream& out,const C1<int>& c) {out << c.value;return out;}

int main()
{
C1<int> c;
cout << c << endl;
return 0;
}


...全文
118 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
csproj 2009-10-09
  • 打赏
  • 举报
回复
谢谢3楼 4楼的二位
我看的教材就写错了,误导了我:
template<class U> //他把这部分没写
friend ostream& operator<<(ostream&,const C1<U>&);
oyster2008 2009-10-07
  • 打赏
  • 举报
回复

#include "iostream"
using namespace std;

template<class T>
class C1
{
template<class U>
friend ostream& operator<<(ostream&,const C1<U>&);
public:
C1(){value = 999;}
private:
int value;
};

//重载<<
template<class T>
ostream& operator<<(ostream& out,const C1<T>& c)
{
out << c.value;
return out;
}



int main()
{
C1<int> c;
cout << c << endl;
return 0;
}


WaistCoat15 2009-10-07
  • 打赏
  • 举报
回复
模板函数定义不明确:

template <class T>
ostream& operator <<(ostream& out,const T& c)
{
out << c.value;
return out;
}

template <class T>
class C1
{
friend ostream& operator << <C1<T>> (ostream&,const C1<T>&);
public:
C1(){value = 999;}
private:
int value;
};

csproj 2009-10-07
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 jackyjkchen 的回复:]
模版的问题,直接在类里面定义吧,或者在h里面反过来include cpp,请看一下模版的两种实例化
[/Quote]
谢谢你,我回去试试。
jackyjkchen 2009-10-07
  • 打赏
  • 举报
回复
模版的问题,直接在类里面定义吧,或者在h里面反过来include cpp,请看一下模版的两种实例化

16,551

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • Creator Browser
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

试试用AI创作助手写篇文章吧