定义类SmallInt类程序中存在的问题
#include <iostream.h>class SmallInt
{
//重载插入和抽取运算符
friend ostream & operator << (ostream &os, SmallInt &si);
friend istream & operator >> (istream &is, SmallInt &si);
public:
SmallInt operator +(const SmallInt &si){return SmallInt(val+si.val);}
SmallInt operator -(const SmallInt &si){return SmallInt(val-si.val);}
SmallInt operator *(const SmallInt &si){return SmallInt(val*si.val);}
SmallInt operator /(const SmallInt &si){return SmallInt(val/si.val);}
SmallInt operator ==(const SmallInt &si){return (val==si.val);}
SmallInt operator <(const SmallInt &si){return (val<si.val);}
SmallInt operator >(const SmallInt &si){return (val>si.val);}
SmallInt operator <=(const SmallInt &si){return (val<=si.val);}
SmallInt operator >=(const SmallInt &si){return (val>=si.val);}
SmallInt(int i=0);
private:
char val;
};
SmallInt::SmallInt(int i)
{
while(i>127)//检查数是否超出范围,是则改为允许的范围
i-=156;
while(i<-128)
i+=256;
val=i;
}
ostream & operator <<(ostream &os, SmallInt &si)
{
os<<(int)si.val;
return os;
}
istream & operator >>(istream &is ,SmallInt &si)
{
int tmp;
is >> tmp;
si=SmallInt(tmp);//调用构造函数给成员赋值
return is;
}
file 2:
# include "samllInt.h"
void main()
{
SmallInt si1,si2;
SmallInt endTag(0);
while(1){
cout<<"Please input two small int(-128~127):\n";
//测试抽取操作符的正确性
cin >> si1 >> si2; //当两个数都为0时结束输入
if((si1 == endTag)&&(si2 == endTag))
break;
//测试插入运算符的正确性
cout<<"si1="<<si1<<"si2="<<si2<<endl;
//测试+-*/运算符的正确性
cout<<"si1+si2"<<si1+si2<<endl;
cout<<"si1-si2"<<si1-si2<<endl;
cout<<"si1*si2"<<si1*si2<<endl;
cout<<"si1/si2"<<si1/si2<<endl;
//测试比较运算符的正确性
cout<<"si1<si2 ?"<<((si1<si2)?"true":"false")<<endl;
cout<<"si1>si2 ?"<<((si1>si2)?"true":"false")<<endl;
cout<<"si1<=si2 ?"<<((si1<=si2)?"true":"false")<<endl;
cout<<"si1>=si2 ?"<<((si1>=si2)?"true":"false")<<endl;
cout<<"si1==si2 ?"<<((si1==si2)?"true":"false")<<endl;
}
}
出现如下问题:
:\clian\mainSamllInt.cpp(10) : error C2676: binary '&&' : 'class SmallInt' does not define this operator or a conversion to a type acceptable to the predefined operator
F:\clian\mainSamllInt.cpp(20) : error C2440: '?' : cannot convert from 'class SmallInt' to 'bool'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
F:\clian\mainSamllInt.cpp(20) : fatal error C1903: unable to recover from previous error(s); stopping compilation
Error executing cl.exe.
mainSamllInt.obj - 3 error(s), 0 warning(s)
smallint.rar
(1.23 KB)