实现头文件的自封闭
来源:互联网 发布:unity3d培训机构 编辑:程序博客网 时间:2024/05/01 08:43
记得以前写的几个课程设计,代码动辄几千行,头文件很多,而且还是互相关联的,所以写起程序总是小心翼翼,以免头文件被重复包含.后来才发现其实有很好的解决办法,只是我不知道而已,或者说是课本中没有,且参考书中也很少提及而已.只恨自己知道的太晚,走了太多的弯路.
就我目前的经验来写写如何实现头文件的自封闭,希望能对大家有所帮助.
1.头文件与实现分开.如以下例子,假如没有分开,那么a.h就不是独立的了,它要受到<stdio.h>的制约,那么编程时就要考虑a.h与stdio.h的先后顺序以及是否stdio.h被重复包含.
///////////////////"a.h"/////////////////////////
class A{
int a;
public:
A(int _a);
void puta();
};
/////////////////"a.cpp"////////////////////
#include"a.h"
#include<stdio.h>
A::A(int _a):a(_a){
}
void A::puta(){
printf("%d",a);
}
//////////////////"main.cpp"///////////////
#include "a.h"
#include<conio.h>
#include<stdio.h>
int main(){
A a(10);
printf("In main:/r/n");
a.puta();
getch();
return 0;
}
2.采用宏定义,避免头文件的重复包含.如以下例子,尽管class B中有成员A b;但若只使用B类的话,就只要包含"b.h"就行了.若还要使用类A的话,就包含"a.h".它们之间互不干扰.在main程序中的包含的先后顺序也无关紧要.
/////////////////"a.h"////////////////
#ifndef INCLUDE_A
#define INCLUDE_A
class A{
int a;
public:
A(int _a);
void puta();
};
#endif
///////////////////"a.cpp"////////////////
#include"a.h"
#include<stdio.h>
A::A(int _a):a(_a){
}
void A::puta(){
printf("A:%d/r/n",a);
}
////////////////////"b.h"////////////////
#ifndef INCLUDE_B
#define INCLUDE_B
#include "a.h"
class B{
A b;
public:
B(int _b);
void putb();
};
#endif
/////////////////////"b.cpp"////////////////
#include "b.h"
#include<stdio.h>
B::B(int _b):b(_b){
}
void B::putb(){
printf("B:");
b.puta();
}
///////////////////"test.cpp"//////////////
#include"stdio.h"
#include"conio.h"
#include "a.h"
#include "b.h"
int main(){
A a(5);
B b(10);
printf("In main:/r/n");
a.puta();
b.putb();
getch();
return 0;
}
另外,如果是在VC下编程的话,可以用#pragma once代替宏定义.如下
/////////////////////"a.h"////////////////////
#pragma once
int a(){
return 0;
}
//////////////////////"a.cpp"//////////////
#include<stdio.h>
#include<conio.h>
#include"a.h"
#include"a.h"
#include"a.h"
int main(){
printf("%d",a());
getch();
return 0;
}
- 实现头文件的自封闭
- 自封闭的html标签
- 顺序表的头文件和头文件的实现
- 头文件与实现文件的关系
- 头文件与实现文件的关系
- 头文件的终极书写原则(转自百度博客)
- WINAVR自带的watch dog函数头文件
- h5头文件里添加的自适配内容
- gcc添加自写头文件的问题解决
- Matlab实现二维的最小封闭球
- 读取PE文件头的简单实现
- 头文件和实现的关系
- 实现在头文件
- 头文件与之实现文件的的关系
- 头文件与之实现文件的的关系~
- 头文件与之实现文件的的关系~ .
- 头文件与之实现文件的的关系~
- 头文件与之实现文件的的关系~
- 《诗盗·手贱》
- 哈希表(转自歪歪狼)
- 基于winbond 950cdg samba for arm9+linux-2.6.17 的 移稙
- 简单的正则(四例)
- hosts文件的作用
- 实现头文件的自封闭
- 读取AD组织架构用户,登陆名
- SQL Server 2005利用分区对海量数据的处理(转载)
- 128 种ajax
- 使用FEST-Swing测试GUI
- Test on quota
- 第一篇
- 小知识
- THU APR 16,2009