这是我使用的代码:gdb一旦启动构造函数,就会显示分段错误。我可能做错了什么?
class Employee
{
public:
string name;
int height;
int level;
Employee* iboss;
Employee* parent;
Employee* left_child;
Employee* right_child;
vector<Employee*> junior;
};
class Company
{
private:
Employee* root;
Employee* rootAVL;
public:
Company(void)
{
root->junior[0]=NULL;
root->level=0;
root->iboss=NULL;
root->height=0;
root->left_child=NULL;
root->right_child=NULL;
root->parent=NULL;
rootAVL=root;
}
Employee* search(string A, Employee* guy,int c);
void AddEmployee(string A,string B);
void DeleteEmployee(string A,string B);
void LowestCommonBoss(string A,string B);
void PrintEmployees();
void insertAVL(Employee* compare,Employee* guy,int c);
void deleteAVL(Employee* guy);
void GetName(string A)
{
root->name=A;
cout<<A;
}
};
int main()
{
cout<<"hello world";
Company C;
//so the problem seems to be that there's a segmentation fault every time i try to access root or try to point to it's methods.
cout<<"hello world";
string f;
cin>>f;
C.GetName(f);
C.PrintEmployees();
}
每当我尝试使用root->junior[0]=NULL
或类似的东西时,它都会给我一个细分错误。
可能是什么问题呢?
在课堂上,Compnay
您有:
Employee* root;
在Company
构造函数中,您可以执行以下操作:
root->junior[0]=NULL;
但是您没有构造任何实例Employee
,因此root
指针无效。因此,您只是尝试使用上述root->junior...
行访问无效的内存。
考虑创建Employee
第一个。
还请注意,如果您这样做了root->junior[0]=...
,则还应将Employee
的std::vector junior
数据成员创建为向量,其中至少包含一项(索引为0的项,您正在尝试访问)。
最后,考虑在C ++ nullptr
11/14NULL
代码中使用insteaad 。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句