注册 登录
编程论坛 C++教室

输入操作符重载问题 operator>> is ambiguous

zhongjiezhe 发布于 2011-07-06 19:36, 1029 次点击
#include<iostream>
#include<stdlib.h>
using namespace std;

class SmallInt
{
public:
    SmallInt(int i=0):value(rangecheck(i))
    {}
    int operator=(int i)
    {
        return (value=rangecheck(i));
    }
    operator int()
    {
        return value;
    }
    friend istream& operator>>(istream &is,SmallInt &s);
    friend ostream& operator<<(ostream &os,const SmallInt &s)
    {
        return os<<s.value;
    }
private:
    int rangecheck(int);
    int value;

};

istream& operator>>(istream &is,SmallInt &s)
{
    int ix;
    is>>ix;
    s=ix;
    return is;
}

int SmallInt::rangecheck(int i)
{
    if(i&~0377)
    {
        cerr<<"\n***SmallInt range error: "
            <<i<<" ***"<<endl;
        exit(-1);
    }
    return i;
}

int main()
{
    SmallInt s1,s2;
    cout<<"enter a SmallInt , please:  ";
    while(1)
    {
        cin>>s1;
        cout<<"the value read is "
            <<s1<<"\nit is ";
        cout<<((s1>127) ? "greater than" :((s1<127) ? "less than" : "equal to"))<<"127\n";
        cout<<"\nenter a SmallInt ,please \
                (ctrl-d to exit): ";

    }
    cout<<"bye now\n";
    system("pause");
    return 0;
}
这是c++ primer3 上的一个例子,编译以后出现'operator >>' is ambiguous 的错误提示
但将头文件换成#include<iostream.h>就可以编译通过而且可以正常运行,这是怎么回事啊
8 回复
#2
玩出来的代码2011-07-06 21:10
没问题,LZ用的什么编译器。
#3
zhongjiezhe2011-07-06 21:21
回复 2楼 玩出来的代码
vc6下得用#include<iostream.h>才能正确运行,不能用#include<iostream> using namespace std;总提示operator>>出错,应该是重载发生二义性吧,搞不清楚是怎么回事
#4
玩出来的代码2011-07-06 22:02
那就换编译器吧,VC6对友元的支持不好。那是编译器的问题
#5
ToBeStronger2011-07-06 23:10
回复 3楼 zhongjiezhe
你的VC6.0没打补丁,鉴定完毕.......
#6
zhongjiezhe2011-07-07 09:45
回复 5楼 ToBeStronger
求补丁名称
#7
ToBeStronger2011-07-07 12:17
回复 6楼 zhongjiezhe
vc6.0 sp6补丁,官方最后一补丁
#8
succubus2011-07-08 09:40
学C++就别用VC6了
VC6出来的时候C++标准还没定好呢
还是用VS2005之类的吧
#9
pangding2011-07-08 12:19
定好了当年MS也没按着标准实现。
1