关于运算符重载的问题

Gzd2003 2008-12-24 09:29:05
存在下面的程序,重载<<运算符,编译出错,错误信息如下:
--------------------Configuration: Test - Win32 Debug--------------------
Compiling...
CopyTest.cpp
D:\Test\CopyTest.cpp(19) : error C2593: 'operator <<' is ambiguous
Error executing cl.exe.
Creating browse info file...

Test.exe - 1 error(s), 0 warning(s)

源程序如下:
#include <iomanip>
#include <iostream>
using namespace std;
class Fun
{
friend ostream & operator<<(ostream & , Fun );
};

ostream & operator<<(ostream & os, Fun f)
{
os.setf(ios::left);
return os;;
}

void main()
{
Fun fun;
cout<< setfill('*') << setw(10) <<12345<<" ";
cout<< fun << setw(10) << 54321 << endl;
}

后来我发现程序改成如下就没有问题。不知道什么道理,各位大哥请指教。
#include <iomanip>
#include <iostream>
using namespace std;
class Fun
{
friend ostream & operator<<(ostream & os, Fun f)
{
os.setf(ios::left);
return os;;
}
};

void main()
{
Fun fun;
cout<< setfill('*') << setw(10) <<12345<<" ";
cout<< fun << setw(10) << 54321 << endl;
}
...全文
34 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
nullah 2008-12-24
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 Gzd2003 的回复:]
补充一下,我使用的是VC6.0
[/Quote]
该换换了
nullah 2008-12-24
  • 打赏
  • 举报
回复
楼主
你的第一个程序在VS2005下编译正常
运行正常
不知道你用的什么编译器
sincor 2008-12-24
  • 打赏
  • 举报
回复
#include <iomanip> 
#include <iostream>
using namespace std;
class Fun //类 Fun
{
friend ostream & operator < <(ostream & , Fun ); //友元函数
};

ostream & operator < <(ostream & os, Fun f)
{
os.setf(ios::left);
return os;;
}

void main()
{
Fun fun;
cout < < setfill('*') < < setw(10) < <12345 < <" ";
cout < < fun < < setw(10) < < 54321 < < endl;
}

后来我发现程序改成如下就没有问题。不知道什么道理,各位大哥请指教。
#include <iomanip>
#include <iostream>
using namespace std;
class Fun
{
friend ostream & operator < <(ostream & os, Fun f)
{
os.setf(ios::left);
return os;;
}
};

void main()
{
Fun fun;
cout < < setfill('*') < < setw(10) < <12345 < <" ";
cout < < fun < < setw(10) < < 54321 < < endl;
}


能注释下吗?你到底要表达什么

好像是对ostream某一函数(运算符)的重载
Gzd2003 2008-12-24
  • 打赏
  • 举报
回复
补充一下,我使用的是VC6.0
sincor 2008-12-24
  • 打赏
  • 举报
回复
等会我运行下

64,682

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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