码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-06-13 17:02:18      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:

#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\n"<<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\n"<<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)\n"<<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;
}

  

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

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!