C + + Two classes that contain references to one another

Source: Internet
Author: User

    • When constructing your own class, it is possible to encounter mutual reference problems between the two classes, for example: a type defined in Class A class b,a is used and a type defined by a is used in B.
  
 
  1. class A
  2. {
  3. B b;
  4. }
  5. class B
  6. {
  7. A* a;
  8. }
    • Note that the definition above, in general, can not appear Class A, class B mutual references are defined objects, that is, the following look:
  
 
  1. class A
  2. {
  3. B b;
  4. }
  5. class B
  6. {
  7. A a;
  8. }
    • When the compiler declares a, a compilation error occurs because the declaration of B is below a
    • Then, in the definition because the mutual reference will certainly need to include the header file, if only in the respective header file contains the other side of the header file, is not compiled, as follows:
  
 
  1. //class A.h
  2. #include "B.h"
  3. class A
  4. {
  5. B b;
  6. }
  7. //class B.h
  8. #include "A.h"
  9. class B
  10. {
  11. A *a;
  12. }
The inclusion method above may cause the compiler to have an error message: The A.h file uses the type B.
What to do?
The general practice is: In the header file of two classes, select a header file containing another class, but the other header file can only be in the form of class *, and in the implementation file (*.cpp) contains the header file, as follows:
  
 
  1. //class A.h
  2. #include "B.h"
  3. class A
  4. {
  5. B b;
  6. }
  7. //class B.h
  8. class A;
  9. class B
  10. {
  11. A *a;
  12. }
  13. //B.cpp
  14. //在B.cpp中的文件包含处要有下面语句,否则不能调用成员a的任何内容
  15. #include "A.h"
  16. B::B()
  17. {
  18. ……
  19. }
Moreover, in B.h, because it is a class A, the way to declare, you can only define a pointer or reference in class B's declaration.


From for notes (Wiz)

C + + Two classes that contain references to one another

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.