经常遇到要进行大整数运算的情况,所以专门写一个大整数类,其中运算符重载的规则参考于《C++ Primer, 4th Edition》。

关于类的实现:

1、基本思想是用标准库中的string来存储数据,一位对应一个字符,首位是符号位,'+’ ‘-'分别代表正负,正号按常规不输出。只有+0,不会有-0出现。

2、实现了5个构造函数,可以用string,常量字符串,int及BigInt类型进行初始化。从而使得BigInt类型的数能够直接跟int类型的数进行运算。(有了构造函数,编译器会自动进行类型转换,vs2008上验证)

3、输入输出及比较运算符是二元运算符,而且要访问类的私有成员,所以重载为友元函数。

4、赋值,+=之类的一元运算符实现为成员函数,++,--也实现为成员函数。其余的加减乘除等二元运算符用实现好的+=等运算符来实现。其中模运算遵从C++的一般习惯,符号跟随第一操作数。即-7%2=-1,7%-2=1,-7%-2=-1

5、由于这个类实现的是有符号的大整数,故实现了无符号的加减及无符号的比较函数作为私有成员函数,仅供实现其他运算之用。其中无符号的减法默认被减数大于减数。

6、整个类的声明,类的定义及相关的操作符重载均实现于一个.h文件中,由于程序太长故分几部分列出。原文件已经包含防止重复定义的宏。

首先列出类的声明:

#include<string>
#include<vector>

using namespace std;

class BigInt
{
    //Input
    friend istream& operator>>(istream&, BigInt&);
    //Output
    friend ostream& operator<<(ostream&, const BigInt&);
    friend bool operator==(const BigInt&, const BigInt&);
    friend bool operator<(const BigInt&, const BigInt&);
    friend bool operator>(const BigInt&, const BigInt&);
public:
    BigInt();
    BigInt(const string&);
    BigInt(const BigInt&);
    BigInt(int);
    BigInt(const char*);
    BigInt& operator=(const BigInt&);
    BigInt& operator+=(const BigInt&);
    BigInt& operator-=(const BigInt&);
    BigInt& operator*=(const BigInt&);
    BigInt& operator/=(const BigInt&);
    BigInt& operator%=(const BigInt&);
    //prefix increment
    BigInt& operator++();
    //prefix decrement
    BigInt& operator--();
    //postfix increment
    BigInt operator++(int);
    //postfix decrement
    BigInt operator--(int);
private:
    //unsigned +=
    void plus(const string&);
    //unsigned -=
    void minus(const string&);
    //unsigned ==
    bool equal(const string&) const;
    //unsigned <
    bool smaller(const string&) const;
    //unsigned >
    bool greater(const string&) const;
    string num;
};