2014-09-12 59 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

相關問題