【发布时间】:2011-02-05 07:47:28
【问题描述】:
我对 c++ 还很陌生,我有点被这个问题难住了。我正在尝试将调用中的变量分配给另一个类中的方法,但它总是出现段错误。我的代码编译时没有任何警告,并且我检查了 gdb 中的所有变量是否正确,但函数调用本身似乎会导致段错误。我使用的代码大致如下:
class History{
public:
bool test_history();
};
bool History::test_history(){
std::cout<<"test"; //this line never gets executed
//more code goes in here
return true;
}
class Game{
private:
bool some_function();
public:
History game_actions_history;
};
bool Game::some_function(){
return game_actions_history.test_history();
}
非常感谢任何提示或建议!
编辑:我编辑了代码,所以没有更多的 local_variable 并且值直接返回。但它仍然存在段错误。至于贴出实际代码,比较大,应该贴哪些部分?
【问题讨论】:
-
我们需要看到真正的代码。
-
local_variable不是很本地化,是吗? :) 它是一个成员变量。此外,测试 bool 以返回该 bool 有点多余:return local_variable;。当然,您也不需要先存储它:return game_actions_history.test_history();无论如何,这段代码“很好”。你可以创建一个Game g;,但你不能调用g.some_function();,它是私有的。如果不是,它会工作得很好。 -
test_history中还有哪些其他代码?您是否尝试过调试器和/或检查内核以查看堆栈转储? -
std::cout<<"test";可能实际上会被执行,但如果没有换行符,它可能不会刷新到屏幕上。 -
发布与指针、数组或手动内存实例化/删除有关的任何内容。
标签: c++ methods segmentation-fault call