首先我们需要定义一个类,它支持传入的是整形,字符串,同时默认参数为0;
其次我们需要重载运算符+,=,重载输出流<<,同时重载输出流时,我们需要用friend定义友元,执行cout<<类的语句;
为了代码的简洁性,我们可以将整形转为字符串来储存。
代码如下
#include <iostream>
#include <string>
using namespace std;
class HugeInteger{
private:
string str;
//定义成员变量
public:
HugeInteger(int i=0){
int n=i,cnt=0;
while(n){
n/=10;
cnt++;
}
//求是几位数
for(int k=1;k<=cnt;k++){
str=char(i%10+'0')+str;
i/=10;
}
//实现从整形转化为字符串;
if(cnt==0) str="0";
//如果时0,我们需要特判一下,因为0是0位数
}
HugeInteger(string Str){
str=Str;
}
friend ostream & operator<<( ostream & os,HugeInteger & c){
os<<c.str;
return os;
}
//友元导包输入输出流
string operator + (const HugeInteger & c){
string b=c.str;
string a=this->str;
while(a.size()>b.size()){
b='0'+b;
}
while(a.size()<b.size()){
a='0'+a;
}
a='0'+a;
b='0'+b;
for(int i=a.size()-1;i>=0;i--){
a[i]=a[i]+b[i]-'0';
if(a[i]>'9'){
a[i]-=10;
a[i-1]+=1;
}
}
if(a[0]=='0') a=a.replace(0,1,"");
return a;
}
//重载加号(类+类)
string operator + (string a){
string b=this->str;
while(a.size()>b.size()){
b='0'+b;
}
while(a.size()<b.size()){
a='0'+a;
}
a='0'+a;
b='0'+b;
for(int i=a.size()-1;i>=0;i--){
a[i]=a[i]+b[i]-'0';
if(a[i]>'9'){
a[i]-=10;
a[i-1]+=1;
}
}
if(a[0]=='0') a=a.replace(0,1,"");
return a;
}
//重载加号(类+字符串)
HugeInteger operator = (string & a){
HugeInteger box(a);
return box;
}
//重载等号
};
int main()
{
HugeInteger n1( 7654321 );
HugeInteger n2( 7891234 );
HugeInteger n3( "99999999999999999999999999999" );
HugeInteger n4( "1" );
HugeInteger n5;
cout << "n1 is " << n1 << "\nn2 is " << n2
<< "\nn3 is " << n3 << "\nn4 is " << n4
<< "\nn5 is " << n5 << "\n\n";
n5 = n1 + n2;
cout << n1 << " + " << n2 << " = " << n5 << "\n\n";
cout << n3 << " + " << n4 << "\n= " << ( n3 + n4 ) << "\n\n";
n5 = n1 + 9;
cout << n1 << " + " << 9 << " = " << n5 << "\n\n";
n5 = n2 + "10000";
cout << n2 << " + " << "10000" << " = " << n5 << endl;
return 0;
}