为了体会用#ifndef/#define#endif来防止头文件被引用(例子)
这一作用,写了个例子来做试验
head1.h begin///
#include <iostream>
using namespace std;
#ifndef HEAD1_H //<1>
#define HEAD1_H //<2>
class b{
public:
int GetData();
b()
{
cout << "An object b is created./n";
};
private:
int*data;
};
#endif //<3>
head1.h end///
head2.h begin///
#include <iostream>
#include "head1.h"
using namespace std;
#ifndef HEAD2_H
#define HEAD2_H
class a{
public:
int GetData();
a(){cout << "An object a is created./n";};
private:
int*data;
};
#endif
head2.h end///
以下是main函数文件
#include "head1.h"
#include "head2.h"
int main()
{
a a1;
b b1;
}
结论:
1.如果将head1.h中的<1><2><3>行注释掉,编译错误:
b class type redifinition
2.加上,正确编译
3.原因就是因为head2.h中包含了head1.h,而且main.cpp中也包含了head1.h
于是会发生重复引用,进而b class会redifinition.
疑问:
1. #ifndef/#define/#endif中的#endif位置必须放在文件末尾吗?(和#ifndef的关系就像左右括号?)
2.两个头文件不能互相包含吗?,比如head1.h中include了head2.h,head2.h中又include了head1.h
其实,只要在头文件的最开始加入#pragma once 这条指令就能够保证头文件被编译一次,这条指令实际上在VC6中就已经有了,但是考虑到兼容性并没有太多的使用它。只要在头文件的最开始加入这条指令就能够保证头文件被编译一次,这条指令实际上在VC6中就已经有了,但是考虑到兼容性并没有太多的使用它。
详见[编译预处理系列5]