Forward Reference Declaration and Complementary Measures in C++ (Object Pointer)

Forward reference declaration
C++ classes should be declared first and then used, but when two classes in the code need to refer to each other, no matter which class is declared first, it will cause undefined class compilation errors.
example:

class A
{
    
    
public:
	void f(B b);//报错信息为:'B' (add forward declaration)?
};
class B
{
    
    
public:
	void f(A a);
};

If you need to refer to a certain class before its declaration, you should make a forward reference declaration, for example:

class B;       //前向引用声明
class A
{
    
    
public:
	void f(B b);//报错信息为:'B' (add forward declaration)?
};
class B
{
    
    
public:
	void f(A a);
};

The forward reference declaration just introduces an identifier for the program, but the specific declaration is elsewhere.

Precautions for forward reference declarations
. Before providing a complete class declaration, you cannot declare objects of this class, nor can you use objects of this class in inline member functions.
When using forward reference declarations, only the declared symbols can be used, and no details of the class can be involved, because the referenced class declaration is not complete, and the class information is incomplete, such as the number of bytes, such as:

#include <iostream>
class B;
using namespace std;

class A
{
    
    
public:
	B b;//报错信息为:Type 'B' is incomplete
	void f(B b);
};
class B
{
    
    
public:
	A a;
	void f(A a);
};

Complementary measures

#include <iostream>
class B;
using namespace std;

class A
{
    
    
public:
	B* b;       //在A类里面定义一个指向B类的指针(只使用被声明的符号)
	            //在主调函数中用new进行动态内存分配,将B的首地址赋给这个指针
	            //这样在 效果上 就完成了两个类相互调用
	void f(B b);
};
class B
{
    
    
public:
	A a;
	void f(A a);
};

Note: In fact, there are relatively few cases where two classes call each other

Guess you like

Origin blog.csdn.net/qq_43530773/article/details/113884131