首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

前几贴的有关问题总结,还是有两处不懂。麻烦老大们看看

2012-02-14 
前几贴的问题总结,还是有两处不懂。麻烦老大们看看#includeiostreamusingnamespacestdostream&operator

前几贴的问题总结,还是有两处不懂。麻烦老大们看看
#include   <iostream>
using   namespace   std;

ostream&   operator < <(ostream&   os,   int&   a)
{
//os < <a;//这出错,为什么下面   endl   的都可以,但就没换行
os.operator   < <(a);
os < <endl;//   为什么这两个输出,没换行?
os.operator   < <(endl);              
return   os;
}

int   main()
{
cout < <1 < <2 < <3;
}

[解决办法]
两个问题都是一个原因:
ostream本身有一个成员operator < < :
ostream& ostream::operator < <(int num); (1)
而楼主又定义了一个全局 operator < <:
ostream& operator < <(ostream& os, int& a) (2)

1. os < <a 出错:
使用(1)还是(2)产生歧义.

2. endl输出无效:
注意cout < <1 < <2 < <3 的参数是常数,不能转成int&,故只能调用(1).也就是说,这儿没有歧义,但是楼主定义的operator < <根本没被用到.
[解决办法]
ostream& operator < <(ostream& os, int& a)
这句最好改称:
ostream& operator < <(ostream& os, const int& a)
否则
os < <1 < <2 < <3;出错,因为字面值常量不能赋给非const的引用

热点排行