Forward declarations in C++
前向声明是一种,不完全类型声明,所以他并不能取代完全类型,对于编译器来说,在需要知其被声明对象大小和内容时,前向声明,己不可用。故其应用场景,仅限如下:
- 1,声明引用和指针
- 2,作函数(仅声明),的返回类型或是参数类型。
下面给出了一个应用场景:
A.h
#ifndef __A__H__
#define __A__H__
#include <string>
class B; // here 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; // Here 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 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;
}
本文介绍了C++中前向声明的应用场景,包括如何使用前向声明来声明引用和指针,以及作为函数的返回类型或参数类型。通过一个具体例子展示了两个相互依赖的类A和B如何利用前向声明来避免头文件之间的循环依赖。
702

被折叠的 条评论
为什么被折叠?



