[编译预处理系列1]用#ifndef/#define#endif来防止头文件被引用(例子)

为了体会用#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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值