如果我在另一个类中使用类的对象,我可以使用指向第一类对象的指针来指向它的成员吗?

时间:2014-09-12 10:26:22

标签: c++ class pointers

以下是我使用过的代码: 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或任何类型的东西时,它都会给我一个分段错误。

可能是什么问题?

1 个答案:

答案 0 :(得分:2)

在课程Compnay中你有:

Employee* root;

并在Company构造函数中执行:

root->junior[0]=NULL;

但是您没有构造Employee的任何实例,因此root指针无效。因此,您只是尝试使用前面提到的root->junior...行访问无效内存。

首先考虑创建Employee

另请注意,如果您执行root->junior[0]=...,则Employee std::vector junior数据成员也应创建为包含至少一个项目的向量(索引0,您正在尝试访问)。

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