C++大数运算与运算符重载

    添加时间:2013-6-25 点击量:

    转载请注明原文地址:http://www.cnblogs.com/yanyojun/p/3153036.html


    应博问里面一个童鞋的请求,写了下面一个法度,主如果大数运算和运算符的重载,时候限制,只做了加法。大神你可以直接略过,见笑见笑,呵呵(PS:写博客的时辰怎么插入神情?)。


    空话不久不多说,法度如下。



    #include <iostream>
    
    #include
    <cstring>
    using namespace std;
    class BigNum
    {
    private:
    char num;
    int length;
    public :
    BigNum();
    BigNum(
    const char );
    BigNum(
    const BigNum & bigNum);
    int print();
    BigNum
    operator + (BigNum);
    BigNum
    & operator =(BigNum);
    };
    BigNum
    & BigNum::operator = (BigNum bigNum)
    {
    this->length=bigNum.length;
    this->num;
    this->num=new char[this->length+1];
    forint i=0;i<this->length;i++
    {
    this->num[i]=bigNum.num[i];
    }
    this->num[length]=\0;
    return this;
    }
    BigNum::BigNum()
    {
    this->length=0;
    }
    BigNum::BigNum(
    const char bigNum)
    {
    this->length=strlen(bigNum);
    num
    =new char[length+1];
    forint i=0;i<length;i++
    {
    this->num[i]=bigNum[length-1-i];
    }
    }
    BigNum::BigNum(
    const BigNum & bigNum)
    {
    this->length=bigNum.length;
    this->num=new char[this->length+1];
    forint i=0;i<this->length;i++
    {
    this->num[i]=bigNum.num[i];
    }
    this->num[length]=\0;
    }
    int BigNum::print()
    {
    forint i=length-1;i>=0;i--
    cout
    <<this->num[i];
    return this->length;
    }
    BigNum BigNum::
    operator + (BigNum bigNum)
    {
    char a;
    int length=max(this->length,bigNum.length);
    a
    =new char[length+2];
    int car=0;
    int i;
    for(i=0;i<length||car!=0;i++
    {
    car
    =this->num[i]-0+bigNum.num[i]-0+car;
    a[i]
    =car%10+0;
    car
    /=10;
    }
    a[i]
    =\0;
    this->num;
    this->num=a;
    return this;

    }
    int main()
    {
    BigNum bigNum_1(
    123456);
    BigNum bigNum_2(bigNum_1);
    bigNum_1.print();
    cout
    <<endl;
    bigNum_2.print();
    cout
    <<endl;
    bigNum_1
    =bigNum_2+bigNum_1;
    bigNum_1.print();
    return 0;
    }


    我所有的自负皆来自我的自卑,所有的英雄气概都来自于我的软弱。嘴里振振有词是因为心里满是怀疑,深情是因为痛恨自己无情。这世界没有一件事情是虚空而生的,站在光里,背后就会有阴影,这深夜里一片寂静,是因为你还没有听见声音。—— 马良《坦白书》
    分享到: