今天看刘汝佳的书,用面向对象的重载用算符打大数,自己也打了篇

#include <iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
#define maxn 1002
struct bign {
	int len,s[maxn];
bign ()
{
	memset(s,0,sizeof(s));
	len=1;
}
 string str() const {
    string res = "";
    for(int i = 0; i < len; i++)
	res = (char)(s[i] + '0') + res;
    if(res == "")
	res = "0";
    //cout<<"string str() const
"<<endl;
    return res;
  }
/*bign operator + (const bign & d)
{

	bign c;
}*/
bign operator + (const bign& b) const
  {
    bign c;
    c.len = 0;
    for(int i = 0, g = 0; g || i < max(len, b.len); i++)
        {
      int x = g;
      if(i < len)
	  x += s[i];
      if(i < b.len)
	  x += b.s[i];
      c.s[c.len++] = x % 10;
      g = x / 10;
    }
   // cout<<" bign operator + (const bign& b) const
"<<endl;
    return c;
  }



bign operator = (const char *num )
{
	int i;
	len=strlen(num);
	for(i=0;i<len;i++)
	{
		s[i]=num[len-1-i]-'0';
	}
	return *this;
}


};
istream & operator >> (istream & in,bign & x)
{
	string s;
	in>>s;
	x=s.c_str();
	return in;
}
ostream& operator << (ostream &out, const bign& x) {
  out << x.str();
  //cout<<"ostream& operator << (ostream &out, const bign& x)
"<<endl;
  return out;
}



/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv) {
	int t,k=1,z;bign a,b,c;

	cin >>t;
	z=t;

		while(t--)
		{
			cin>>a>>b;//简单的调用自己写的函数
			c=a+b;//加法是将左边的对象作为引用传入到重载运算符+中,这儿的=并没有使用重载用算符,只需要系统的足以
			//cout<<c;
			cout << "Case "<<k<<":"<<endl;
			if(k!=z)
  cout <<a<<" + "<<b<<" = "<< c << endl<<endl;
  else cout <<a<<" + "<<b<<" = "<< c << endl;
  k=k+1;//输出流也是自己写的重载函数
		}




	return 0;
}

  

原文地址:https://www.cnblogs.com/41412179guo/p/4573644.html