【发布时间】:2016-02-11 03:36:27
【问题描述】:
我一直在努力理解多态性和指针,但这个概念让我有些不知所措。幸运的是,我有 stackoverflow 和 google,所以我的大部分问题都可以轻松解决。但是,我已经尝试修复这个分段错误几个小时了,但没有运气,我不确定是什么问题。我已经剥离了所有内容以尝试了解出了什么问题,但我相信我缺少动态分配的核心概念。
我将一个字符指针传递给我的函数初始化,我不能在函数内动态分配它吗?我的代码可以编译,但在为(预期的)开关提供输入后,出现分段错误和核心转储。
但是,如果我排除函数初始化并仅在我的主函数中运行代码,则不会出现任何中断,并且 zed 会正确初始化为野蛮人类型。
#include "character.h"//abstract class
#include "barbarian.h"//inherits character
void initialize(character *object){//gets the values for the object
//and lets user deem which type of object
int x=0;
cout<< "1. Barbarian."<<endl;
cout<< "2. Gollum."<<endl;
cout<< "3. Baba Yaga."<<endl;
cout<< "4. Blue Men Group."<<endl;
cout<< "5. Unicorn."<<endl;
while(!(cin>>x)){
cout<<"Input not valid."<<endl;
cin.clear();
cin.ignore(10000,'\n');
}
cout<<"Input is: "<<x<<endl; //debug line
object = new barbarian("conan"); //seg fault here
//down here is a switch that was excluded for this question
}
void die(character *kill){//is now kill
delete kill;
} //this should delete the character after it is used
int main(){
srand(time(0));//used for roll functions in the parent class
cout<<(-time(0))<<"seconds until 1970"<<endl;//debug makes sure srand is
//doing what I want it to
character* zed; //zed = new barbarian("conan");//In main this works
initialize(zed);
//zed = new barbarian("conan"); This works
(*zed).atkRoll();
(*zed).defRoll();
die(zed);
}
我希望能够传递一个字符指针,然后将它作为用户选择的类分配到堆上,并在 main 调用的其他函数中使用它。我认为可以只传递指针并将其作为函数中的参数。然后本地指针将指向与 main 中的指针相同的位置。当函数作用域关闭并且“对象”被删除时,main 中的指针应该保持指向野蛮人的内存位置。这无效吗?如果是这样,我能做些什么作为替代方案? 不告诉指针就不能在main中改变指针的类型吗?
我很困惑>.
【问题讨论】:
-
你需要传递一个指针指针。目前你只是传递一个指针的值,然后在你的初始化函数中覆盖该值的本地副本。
标签: c++ pointers segmentation-fault