Forward declarations in C + +
A forward declaration is an incomplete type declaration, so he cannot replace the complete type, and for the compiler, the forward declaration is not available when it is necessary to know the size and content of the object being declared. So its application scenario is limited to the following: 1, declaring references and pointer 2, as functions (declaration only), return type or parameter type.
Here's an application scenario:
A.h
#ifndef __a__h__
#define __A__H__
#include <string>
class B; This is the forward declaration
class A {public
:
B getbfroma ();
std::string who_are_you ();
};
#endif
B.h
#ifndef __b__h__
#define __B__H__
#include <string>
class A; This is the forward declaration
class B {public
:
A Getafromb ();
std::string who_are_you ();
};
#endif
A.cpp
#include "A.h"
#include "B.h"
B a::getbfroma () {return
B ();
}
std::string a::who_are_you () {return
"I am A";
}
B.cpp
#include "B.h"
#include "A.h"
a B::getafromb () {return
a ();
}
std::string b::who_are_you () {return
"I am B";
}
Main.cpp
#include "A.h"
#include "B.h"
#include <iostream>
int main () {
A;
b b;
A ab = B.getafromb ();
B ba = A.getbfroma ();
Std::cout << "AB is:" << ab.who_are_you () << Endl;
Std::cout << "BA is:" << ba.who_are_you () << Endl;
return 0;
}