2014-09-12 60 views
0

下面是我使用的代码: 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或诸如此类的事分割错误。

可能是什么问题?

+0

提示:当'Company()'构造函数开始执行时'root'指针指向哪里? – Angew 2014-09-12 10:28:30

+0

根点没有特别的地方,所以当你用它去除它会发生什么 - > – ldgorman 2014-09-12 10:29:54

+1

我会建议阅读更多的指针 – ldgorman 2014-09-12 10:30:46

回答

2

在类Compnay您有:

Employee* root; 

Company构造你做:

root->junior[0]=NULL; 

但你并没有建设的Employee任何实例,所以root指针是无效。所以你只是想用前面提到的root->junior...行来访问无效的内存。

首先考虑创建Employee

还请注意,如果这样做root->junior[0]=...,然后也Employeestd::vector junior数据成员应包含至少一个项(具有索引0,则试图访问)的矢量创建。

最后,考虑在C++ 11/14代码中使用nullptr内嵌NULL

相关问题