静态成员函数c ++中的分段错误
Segmentation fault in static member function c++
class Adder {
public:
static int Solve(int a, int b) {return a + b;}
};
class Substructor {
public:
static int Solve(int a, int b) {return a - b;}
};
class Comparer {
public:
static bool Solve(int a, int b) {return a < b;}
};
class If {
public:
static int Solve(bool term, int a, int b) {return term ? a : b;}
};
class Fibo {
public:
static int Solve(int num) {
int res =
If::Solve(
Comparer::Solve(num, 2),
1,
Adder::Solve(
Fibo::Solve(Substructor::Solve(num, 1)),
Fibo::Solve(Substructor::Solve(num, 2))
)
);
return res;
}
};
int calc(int x) {
return Fibo::Solve(x);
}
#include <iostream>
int main() {
std::cout << calc(5) << '\n';
return 0;
}
此代码导致分段错误。我分别测试了所有 类 ,编写了没有其他静态成员函数的递归 fibo 静态成员函数并且它可以工作。结合时它会粉碎。如何修复它以及为什么它会损坏?
问题出在这里:
class Fibo {
public:
static int Solve(int num) {
int res =
If::Solve(
Comparer::Solve(num, 2),
1,
Adder::Solve(
Fibo::Solve(Substructor::Solve(num, 1)),
Fibo::Solve(Substructor::Solve(num, 2))
)
);
return res;
}
};
在 If::Solve()
句子中,如果 Comparer::Solve(num, 2)
检查 num<2,return 1 并且不计算剩余的表达式 Fibo::Solve(Substructor::Solve(num, 1))
和第二个,它不会像你预期的那样工作。要评估 If::Solve()
,必须先评估每个参数才能传递给 If::Solve()
。当它一次又一次地递归计算时,发生堆栈溢出,因此程序终止。如果你真的想做到运行,修改如下:
class Fibo {
public:
static int Solve(int num) {
if (Comparer::Solve(num, 3)) {
return 1;
}
else return Adder::Solve(
Fibo::Solve(Substructor::Solve(num, 1)),
Fibo::Solve(Substructor::Solve(num, 2))
);
}
};
这保证如果 num 是 1 或 2,return 1 并且不会计算剩余的表达式。
class Adder {
public:
static int Solve(int a, int b) {return a + b;}
};
class Substructor {
public:
static int Solve(int a, int b) {return a - b;}
};
class Comparer {
public:
static bool Solve(int a, int b) {return a < b;}
};
class If {
public:
static int Solve(bool term, int a, int b) {return term ? a : b;}
};
class Fibo {
public:
static int Solve(int num) {
int res =
If::Solve(
Comparer::Solve(num, 2),
1,
Adder::Solve(
Fibo::Solve(Substructor::Solve(num, 1)),
Fibo::Solve(Substructor::Solve(num, 2))
)
);
return res;
}
};
int calc(int x) {
return Fibo::Solve(x);
}
#include <iostream>
int main() {
std::cout << calc(5) << '\n';
return 0;
}
此代码导致分段错误。我分别测试了所有 类 ,编写了没有其他静态成员函数的递归 fibo 静态成员函数并且它可以工作。结合时它会粉碎。如何修复它以及为什么它会损坏?
问题出在这里:
class Fibo {
public:
static int Solve(int num) {
int res =
If::Solve(
Comparer::Solve(num, 2),
1,
Adder::Solve(
Fibo::Solve(Substructor::Solve(num, 1)),
Fibo::Solve(Substructor::Solve(num, 2))
)
);
return res;
}
};
在 If::Solve()
句子中,如果 Comparer::Solve(num, 2)
检查 num<2,return 1 并且不计算剩余的表达式 Fibo::Solve(Substructor::Solve(num, 1))
和第二个,它不会像你预期的那样工作。要评估 If::Solve()
,必须先评估每个参数才能传递给 If::Solve()
。当它一次又一次地递归计算时,发生堆栈溢出,因此程序终止。如果你真的想做到运行,修改如下:
class Fibo {
public:
static int Solve(int num) {
if (Comparer::Solve(num, 3)) {
return 1;
}
else return Adder::Solve(
Fibo::Solve(Substructor::Solve(num, 1)),
Fibo::Solve(Substructor::Solve(num, 2))
);
}
};
这保证如果 num 是 1 或 2,return 1 并且不会计算剩余的表达式。