简体   繁体   English

标识符“ xxx”未定义,类指针和结构

[英]identifier “xxx” is undefined, class pointer and struct

I am writing a small c++ - program containing a similar structure to the following: 我正在编写一个小型c ++程序,其中包含与以下内容类似的结构:

class A {
   B * someObjects;
};

typedef A* APointer;

struct B{
   APointer a;
   int n;
}

Trying to compile this gives a "identifier is undefined" error since struct B is not known inside class A. Otherwise declaring struct B before class A should still give a similar error, since then B does not know APointer, or APointer does not know A. Is there any possibility to make class A and struct B being good friends? 尝试编译它会产生“标识符未定义”错误,因为在类A内部未知结构B。否则,在类A之前声明结构B仍应给出类似的错误,因为这样B便不知道APointer或APointer不知道A 。是否有可能使A类和B类成为好朋友? Thanks in advance! 提前致谢!

You need to forward declare B as the compiler has no idea what B is when it is used in A . 您需要转发声明B因为编译器不知道在A使用B时是什么。 B is considered an incomplete type in A and you are allowed to have a pointer or reference to B in A . B被认为是不完整的类型A和你被允许有一个指针或引用BA You can change your code to: 您可以将代码更改为:

struct B;

class A {
   B * someObjects;
};

typedef A* APointer;

struct B{
   APointer a;
   int n;
};

Have you ever heard the term Forward Declaration ! 您是否听说过“ 前向宣言”一词! Your compiler don't know about B yet. 您的编译器还不了解B So give a declaration of B first. 因此,请先声明B

struct B; // forward declaration 

class A {
   B * someObjects;
};
//... rest of the code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM