大数
当一些数字超过整型的上限,那么该如何存储这些数字呢,那就要使用大数来存储。
class BigNumber
{
private:
vector<int> _vec;
bool fag;//判断正负号true代表负号,false代表正号
friend ostream& operator<<(ostream& out, const BigNumber& num);//设置友元方便其他函数使用类内成员
friend istream& operator>>(istream& in, BigNumber& num);
public:
BigNumber() :fag(false) {
};
BigNumber(int num) //利用整型构造
{
fag = false;
if (num < 0)
{
num = -num;
fag = true;
}
int tmp;
while (num)
{
tmp = num % 10;
_vec.push_back(tmp);
num = num / 10;
}
}
BigNumber(string num) //利用字符串构造
{
if (num.size() == 0) return;
fag = false;
int i = 0;
if (num[0] == '-')
{
fag = true;
i++;
}
for (; i < num.size(); i++)
{
_vec.push_back(char_to_int(num[i]));
}
reverse(_vec.begin(), _vec.end());
while (_vec.size() > 1 && _vec[_vec.size() - 1] == 0)
_vec.pop_back();
}
BigNumber(const char* num) //利用char*类型构造
{
if (strlen(num) == 0) return;
fag = false;
int i = 0;
if (num[0] == '-')
{
fag = true;
i++;
}
for (; i <strlen(num); i++)
{
_vec.push_back(char_to_int(num[i]));
}
reverse(_vec.begin(), _vec.end());
while (_vec.size() > 1 && _vec[_vec.size() - 1] == 0)
_vec.pop_back();
}
void show() //依次push进入vector容器,所以要逆向打印
{
if (fag)
{
cout << "-";
}
for (int i = _vec.size() - 1; i >= 0; i--)
{
cout << _vec[i];
}
cout << endl;
}
BigNumber(const BigNumber& num):_vec(num._vec)//拷贝构造
{
fag = num.fag;
_vec = num._vec;
}
void operator=(const BigNumber& num)//等号运算符重载
{
fag = num.fag;
_vec = num._vec;
}
template<typename T>//利用模板将string类型,int类型,char*类型的重载一次搞定
void operator=(T num)
{
*this = BigNumber(num);
}
BigNumber operator+(const BigNumber& num)//加号运算符的重载
{
int size;
BigNumber tmp;
if (fag == true