当前位置:网站首页>Record a circular reference problem

Record a circular reference problem

2022-06-26 04:42:00 Hello,C++!

1、 explain : object A To the object B reference , At the same time B It also refers to objects A, Causes a circular reference .

1.1、 Examples of errors are as follows :

A.h

#pragma once
#include "B.h"

class A
{
    
public:
	B b;
};

B.h

#pragma once

class A;

class B
{
    
public:
	A a;
};
1.2、 Compiler error :

 Insert picture description here

1.3、 The reason for the error :

stay A.h:2, Processing statements #include “B.h”, Expand the header file
stay B.h:5 It is carried out in class B Declare a A A member variable of type , And then class A Not yet declared
So compile error :‘A’ does not name a type

1.4、 There are two ways to solve the problem of circular dependency :

1. Use forward declarations (forward declaration)
2. Avoid circular references at the design level

2、 The statement in the preceding paragraph

2.1、 The role of forward declarations :

1. Unwanted include The header file , The introduction of a large number of header files will cause compilation to slow down
2. It can solve the case that two classes call each other circularly

2.2、 matters needing attention :

Classes that are not defined because of forward declarations are incomplete , therefore class A Can only be used to define pointers 、 quote 、 Or pointers and references to function parameters , Cannot be used to define objects , Or access the members of the class .
This is because we need to determine class B The size of the space occupied , And type A There is no definition yet, and the size cannot be determined , but A Is the pointer type size known , therefore Class B Can be used in A Define member variables .

2.3、 For the characteristics of forward declarations , Revised as follows :

1、 Change the object to an object pointer
2、B In the file of , Use A Make a statement before

Examples are as follows :
A.h

#pragma once
#include "B.h"

class A
{
    
public:
	B* b;
};


B.h

#pragma once

class A;

class B
{
    
public:
	A* a;
};

3、 Avoid circular references at the design level

explain : use C++ The polymorphic characteristics of , Extract abstract classes . Use the parent class pointer 、 Subclass objects solve circular dependencies , Let the concrete depend on the abstract parent class .

The implementation is as follows :

IA.h

class IA
{
    
}

A.h

#include "IA.h"
#include "B.h"
class A : public IA
{
    
	B* b;
}

B.h

#include "IA.h"
class B
{
    
public:
	B(IA* ia) {
     m_ia = ia; }
private:
	IA* m_ia;
}

main.cpp

IA* ia = new A();
原网站

版权声明
本文为[Hello,C++!]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206260431461410.html