设计一个简单的SmallInt类,用来表示从-128到127之间的整数。类的唯一的数据成员val存放一个-128到127(包含-128和127这两个数)之间的整数。 【注意】构造SmallInt类对象时,当给定整数不在指定范围时,需要做相应正规化处理。所谓正规化处理就是当成员数据val的值大于127时,就要减去256,当val的值小于-128时,就需要加上256,直到满足要求为止。 main函数已给定,提交时只需要提交main函数外的代码部分。 #include<iostream> using namespace std; //你提交的代码在这里 int main() { SmallInt s1,s2,s3; cin>>s1>>s2; s3=s1+s2; cout<<s1<<" + "<<s2<<" = "<<s3<<endl; s3=s1-s2; cout<<s1<<" - "<<s2<<" = "<<s3<<endl; s3=s1*s2; cout<<s1<<" * "<<s2<<" = "<<s3<<endl; s3=s1/s2; cout<<s1<<" / "<<s2<<" = "<<s3<<endl; return 0; }输入1 2输出1 + 2 = 3 1 - 2 = -1 1 * 2 = 2 1 / 2 = 0请补充完整代码
时间: 2023-10-30 15:35:30 浏览: 63
c++实现的任意大整数类,是c++新手练手的良好材料 定义可处理任意大的正整数类LongLongInt,用一个动态字符数组存放任
5星 · 资源好评率100%
```
#include<iostream>
using namespace std;
class SmallInt{
private:
int val;
void normalize(); // 辅助函数,用于正规化处理
public:
SmallInt(int v = 0): val(v){ normalize(); } // 构造函数
friend istream& operator>>(istream& in, SmallInt& s); // 输入操作符重载
friend ostream& operator<<(ostream& out, const SmallInt& s); // 输出操作符重载
friend SmallInt operator+(const SmallInt& s1, const SmallInt& s2); // 加法操作符重载
friend SmallInt operator-(const SmallInt& s1, const SmallInt& s2); // 减法操作符重载
friend SmallInt operator*(const SmallInt& s1, const SmallInt& s2); // 乘法操作符重载
friend SmallInt operator/(const SmallInt& s1, const SmallInt& s2); // 除法操作符重载
};
void SmallInt::normalize(){
while(val < -128) val += 256;
while(val > 127) val -= 256;
}
istream& operator>>(istream& in, SmallInt& s){
in >> s.val;
s.normalize();
return in;
}
ostream& operator<<(ostream& out, const SmallInt& s){
out << s.val;
return out;
}
SmallInt operator+(const SmallInt& s1, const SmallInt& s2){
SmallInt res(s1.val + s2.val);
return res;
}
SmallInt operator-(const SmallInt& s1, const SmallInt& s2){
SmallInt res(s1.val - s2.val);
return res;
}
SmallInt operator*(const SmallInt& s1, const SmallInt& s2){
SmallInt res(s1.val * s2.val);
return res;
}
SmallInt operator/(const SmallInt& s1, const SmallInt& s2){
SmallInt res(s1.val / s2.val);
return res;
}
int main(){
SmallInt s1, s2, s3;
cin >> s1 >> s2;
s3 = s1 + s2;
cout << s1 << " + " << s2 << " = " << s3 << endl;
s3 = s1 - s2;
cout << s1 << " - " << s2 << " = " << s3 << endl;
s3 = s1 * s2;
cout << s1 << " * " << s2 << " = " << s3 << endl;
s3 = s1 / s2;
cout << s1 << " / " << s2 << " = " << s3 << endl;
return 0;
}
```
阅读全文