我实现了一个名为的类bignumber
,它将一个大数字作为一个字符串并将其存储在一个数组中。
我为它交了一个朋友operation +
来添加两个大数字。运行后,我收到程序没有响应的错误。问题是什么?
.h 文件:
class bignumber
{
private:
int *number;
int size;
string num;
public:
bignumber(int);
bignumber(string ,int);
~bignumber();
friend bignumber operator+(bignumber,bignumber);
};
定义:
bignumber :: bignumber(int numsize)
{
this->size= numsize;
this->number= new int[size];
};
bignumber :: bignumber(string inputnum,int numsize)
{
int *number = new int[numsize];
size = numsize;
num = inputnum;
for(int i=0;i<numsize;i++){
number[i] = int(num[i])-48;
};
};
bignumber :: ~bignumber()
{
delete [] number;
};
bignumber operator+(bignumber num1,bignumber num2)
{
if(num2.size>num1.size){
int e = num2.size - num1.size - 1;
int *tempnum = new int [num2.size];
for(int i=0;i<num1.size;i++){
tempnum[e+i] = num1.number[i];
}
delete [] num1.number;
num1.number = new int[num2.size];
for(int i=0;i<num2.size;i++){
num1.number[i] = tempnum[i];
}
delete [] tempnum;
}
else if(num1.size>num2.size){
int e = num1.size - num2.size - 1;
int *tempnum = new int [num1.size];
for(int i=0;i<num2.size;i++){
tempnum[e+i] = num2.number[i];
}
delete [] num2.number;
num2.number = new int[num1.size];
for(int i=0;i<num1.size;i++){
num2.number[i] = tempnum[i];
}
delete [] tempnum;
}
bignumber temp(max(num1.size,num2.size));
int carry = 0;
for(int i = 0;i < temp.size;i++){
temp.number[i] = num1.number[i] + num2.number[i] + carry;
if (temp.number[i] > 10){
temp.number[i] -= 10;
int carry = 1;
}
};
if(carry = 1){
int *temp2 = new int[temp.size+1];
temp2[0] = carry;
for(int j = 1;j < temp.size+1;j++){
temp2[j] = temp.number[j-1];
};
temp.size += 1;
delete [] temp.number;
temp.number = new int[temp.size];
for(int i=0;i<temp.size;i++){
temp.number[i] = temp2[i];
}
delete [] temp2;
};
};
另外我不知道如何定义operator >>
输入数字。我是作为朋友写的,但它不起作用:
istream& operator>>(string s,int size)
{
bignumber(s,size);
};