解决了!我发现了我的错误......我在最后发布了我的解决方案。抱歉浪费时间。
我已经有一段时间没有玩c++了。它从来都不是我的主要语言,所以我不熟悉更精细的细节。我弹出一个奇怪的错误。当我调用 factorize() 时,它正在重置数字的符号。尽管从未触及该标志。
我找到了解决方法。在我的工作代码中,我添加了一个整数来保存和重置该值,但我认为我不必这样做。我从下面的代码示例中删除了这两行。
我重置标志的地方: 此类的构造函数将符号设置为 0。它可以在 * 和 *= 运算符中设置为 0(如果它们都具有相同的符号)。仅当将 (unsigned long long) 值分配给对象时,= 运算符才将其设置为零(如果将其设置为另一个 FactorNumber,它会保留符号)。
就是这样。这些是我将符号设置为零的唯一地方。我不明白为什么这个函数会调用其中的任何一个。但是,我并不真正了解 c++ 在处理类时如何做事的细节。我不明白为什么符号一直重置为 0,但也许我做错了什么。有人知道为什么会这样吗?
class FactorNumber {
private:
unsigned long long number;
unsigned long long factor_list[63]; // this is the max possible amount
int number_of_factors;
int sign; // 0=positive 1=negative
void factorize();
[snipped irrelevant public function calls]
};
void FactorNumber::factorize() {
int x=0;
for(x=0;x<64;x++) {
factor_list[x]=0;
}
number_of_factors=0;
unsigned long long current_factor=2; // 64 bits in c++
unsigned long long current_number=number;
unsigned long max_factor=0; // can never be more than 32 bits
if (number>3) {
max_factor=sqrt(current_number);
while (current_factor<=max_factor) {
if(current_number%current_factor) {
if(current_factor>2) {
current_factor+=2;
} else {
current_factor=3;
}
} else {
factor_list[number_of_factors++]=current_factor;
current_number=current_number/current_factor;
if(current_number%current_factor) {
max_factor=sqrt(current_number);
}
}
}
// If there is a number larger than one, add it to the array.
if(current_number>1) {
factor_list[number_of_factors]=current_number;
} else {
number_of_factors--; // If not, we ignore this last number
}
} else {
number_of_factors=0;
factor_list[0]=number;
}
}
我的错误是欧比旺错误。我正在写超出数组末尾的内容(factor_list[63] 实际上并不存在)并且覆盖了我的数据。只是巧合,这个重置标志并没有搞砸其他东西(或者可能搞砸了,但我还没有发现)。这就是我问这个问题的原因。并不是我无法解决它,我知道我的代码中某处存在错误。
将 for 循环条件更改为 x<63 清除了错误。
最佳答案
你在第一个满溢 for
在 factorize()
,因为你要到索引 63,而最大索引(在类中声明为 62(大小 63))。实际上每当你调用factor_list[X]=Y
您有机会超越类(class)中的下一位成员。您始终需要验证数组索引!
unsigned long long factor_list[63]; // <----- indexes from 0 to 62
// <code omitted>
factor_list[666] = 0; // <----- Oops! Overflowing (but it's still valid code)
此外,为什么在 C++ 中使用 C 风格的数组而不是 C++ 风格的数组? std::array
是更好的方法。
关于c++ - 类函数更改类cpp中的其他数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23611609/