c++ class 类名 和 include 的区别

A.h

class A{
public:
    B* m_;
}
1
2
3
4
这样会编译出错,因为B没有定义

#include "B.h"

class A{
public:
    B* m_;
}
1
2
3
4
5
6
但是这样,一旦B的定义修改,那么A.h也就会重新编译,导致所有用到A.h的文件也需要重新编译,这样就造成了编译依赖,增加了编译的时间,在大型项目中,如果很多这样的地方的话,甚至可能极度增加编译时间。为了避免这种情况,我们可以这么做 用 class B;

A.h


class B;
class A{
public:
    B* m_;
}
1
2
3
4
5
6
A.cpp

#include "B.h"
#include "A.h"
//具体实现
1
2
3
通过在A.h中声明class B,在A.cpp中include B.h,这样即使B.h改变,A.h也不会改变,其他使用到A.h的文件也就不需要重新编译了,这样就可以避免编译依赖,在大型项目中会节省很多时间
 

发布了352 篇原创文章 · 获赞 115 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/Aidam_Bo/article/details/105230272