In which order should classes be declared in C++?

2019-02-14 14:19发布

Say I got this C++ code:

class class1{
    class2 *x;
}

class class2{
    class1 *x;
}

The compiler would give an error in line 2 because it couldn't find class2, and the same if i switched the order of the classes. How do I solve this?

标签: c++ class order
3条回答
Melony?
2楼-- · 2019-02-14 14:52

Declare class2 first:

class class2;
class class1{
    class2 *x;
};

class class2{
    class1 *x;
};
查看更多
趁早两清
3楼-- · 2019-02-14 15:14
霸刀☆藐视天下
4楼-- · 2019-02-14 15:15

Two things - one, you need semicolons after class declarations:

class class1{
    class2 *x;
};

class class2{
    class1 *x;
};

Two, you can create a declaration in front of the definitions of the classes. That tells the compiler that this class exists, and you have yet to define it. In this case, put a class2 declaration in front of the definition of class1:

class class2 ;

class class1{
    class2 *x;
};

class class2{
    class1 *x;
};
查看更多
登录 后发表回答