首页 > 其他 > 详细

#ifndef #define #endif

时间:2015-03-24 09:16:16      阅读:172      评论:0      收藏:0      [点我收藏+]
在做程设作业的过程中发现标答都会有一句#ifndef XXX 和 #endif,是什么意思呢?

这是#——预处理运算符的三种用法之一:条件编译
#的用法:
1、包含文件,如#include<stdio.h>
2、宏定义,如#define max_length 100
3、条件编译,如#ifndef、#endif

条件编译是什么意思呢
ifndef其实是if not define的缩写,如果没有定义,那就定义,直到endif

看一个例子:

#include <iostream>
using namespace std;

#ifndef max_length
#define max_length 50
#endif

#ifndef max_length
#define max_length 100
#endif

int main() {
    cout << max_length << endl;
    return 0;
}
那么输出结果显然是50了,由于max_length已经定义为50了,定义为100的部分没有执行。

技术分享

当然这个用法还有避免重复包含头文件的作用,看这个例子
test_main.cpp:
#include <iostream>
using namespace std;

#include "test1.h"
#include "test.h"

int main() {
    test t;
    return 0;
}
test.h:
#include <iostream>
using namespace std;

#ifndef _TEST_H
#define _TEST_H

class test {
  public:
    test() {
        cout << "Test has been constructed." << endl;
    }
};

#endif
test1.h:
#include <iostream>
using namespace std;

#ifndef _TEST_H
#define _TEST_H

class test {
  public:
    test() {
        cout << "Test 1 has been constructed." << endl;
    }
};

#endif
注意在test_main中,我们先#include "test1.h",那么在下一个#include "test.h"中由于已经定义了_TEST_H标识,就不会再定义test.h里面的test类,注意一般标识的写法是下划线+头文件名大写+下划线+H,如_TEST_H,那么输出显然是:

技术分享
假如调换#include "test1.h"和#include "test.h"的顺序:

技术分享

还有一个有趣的现象,在因为已经定义而不会被编译的头文件里,就算有错误也没事,这是因为根本没被编译
注意下面是先#include "test.h"的
技术分享

但是乱打的错误必须在标识内部:

技术分享

还有一些奇怪的东西:

技术分享

#ifndef #define #endif

原文:http://blog.csdn.net/u012925008/article/details/44575635

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!