What is the purpose of a forward declaration?

what is the description or meaning of this: for example:

class test;

class test
{
  .....
};
+5
source share
6 answers

C ++ (e.g. C) was designed to be implemented by a single-pass compiler. Direct references are necessary in cases where the compiler needs to know that the symbol belongs to the class before the class is defined. A classic example of this is when two classes must contain pointers to each other. i.e.

class B;

class A {
  B* b;
};

class B {
  A* a;
};

Without a direct reference to B, the compiler could not successfully parse the definition for A, and you cannot fix the problem by setting definition B to A.

In a language like C #, which requires a two-pass compiler, you don't need direct links

class A {
  B b;
}

class B {
  A a;
}

. , : " , B - , ".

+21

, / . . . :

class A { 
  B m_b; 
  C* m_ptrC;
}; 

B ( ), C ( ). B, C. C .

:

#ifndef A_H
#define A_H

#include <b.h>
class C;

class A
{
  B m_b;
  C* m_ptrC;
}
#endif

- c ( c.h, ) c.h , a.h. . , c.h a . , , c.h , .

pimpl-idiom ( Google , ).

- a.cpp, - c (, m_ptrC- > Add()), c.h. a.cpp , n n , .

. :

class B;

class A {
 B* m_ptrB;
}

class B {
 A* m_ptrA;
}

- - , . , ( , ). , - , , .

: ++

, .

+7

, .

: : , - (, ..), . -.

: : , ( ) , .. . - , .

.

+4

- , . .

+1

, . test , (...).

0

The simple answer is that when using the first form, you can hold pointers or references for a class without requiring a full implementation. This can be very useful when the two classes interact closely, and their implementation or definitions are difficult to separate.

0
source

All Articles