我制作了一个 MegaInt 类,可以处理非常大的数字并重载了一些运算符。不幸的是,我卡住了,我的代码崩溃了。
每个 MegaInt ojb 都有一个 vector 值和一个 bool 符号。一个数的每个位置放在 vector 中(即4325是 vector 值={5,2,3,4}),它的符号(+或-)是1还是0。
这里有一些代码...
#include <vector>
#include <string>
using namespace std;
class MegaInt{
friend class main;
private:
vector<int> value;
bool sign; //true is pos, false is neg
public:
MegaInt(vector <int> x, bool y);
MegaInt(string s);
MegaInt(const MegaInt& m);
MegaInt & operator*=(const MegaInt &rhs);
#include <iostream>
using namespace std;
#include "MegaInt.h"
#include <math.h>
MegaInt::MegaInt(string s){
int pos = s.length()-1;
while (pos >= 0){
if(pos == 0 && s[pos] == '-'){
sign = false;
break;
}
else if (pos == 0 && s[pos] == '+'){
sign = true;
break;
}
else{
sign = true;
}
if(s[pos] >= 48 && s[pos] <= 57)
value.push_back(s[pos]-48);
else{
value.clear();
break;
}
pos --;
}
chopoffleadingOs();
}
MegaInt::MegaInt(const MegaInt& m){
value = m.value;
sign = m.sign;
}
MegaInt operator*(const MegaInt& x, const MegaInt& y){
int multi = 0;
int temp;
vector<int> total;
for(int i = x.value.size()-1; i>=0; --i){
for(int j = y.value.size()-1, k = 0; j>=0; --j, ++k){
temp = x.value[i] * y.value[j];
if (total.size() <= (i + multi + 1))
total.resize(i + multi + 1 + 1);
total[i + multi] += (temp % 10);
temp = (temp - total[i]) / 10;
total[i + multi + 1] += temp;
}
multi++;
}
reverse(total.begin(), total.end());
return newTotal;
}
我似乎主要停留在重载的乘法部分。剩下的我想我得到了。
谢谢, 诺亚
最佳答案
问题可能出在这里:
total[i+multi]+=(8%10);
您使用了total
vector ,但尚未为其分配内存。这可以通过 resize
来完成。功能:
total.resize(MAX_SIZE);
查找意外崩溃的一个好方法是使用调试器。如果您在调试器中运行该程序,它会在出现问题时停止,因此您可以检查变量并查看崩溃的位置和可能导致崩溃的原因。
编辑:
如果事先不知道total
vector 的大小,则必须动态调整它的大小:
if (total.size() <= (i + multi + 1))
total.resize(i + multi + 1 + 1); // An extra +1 because vectors are zero-indexed
total[i+multi]+=(8%10);
// ...
关于c++ - C++ 中的重载运算符 - 编译但崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9697088/