
2个回答
展开全部
#include指令的缺陷,导致同一个头文件会被多次引入,使用ifndef可以避免多次引入。
例如一个程序中包含如下文件:dialog.cpp dialog.h network.cpp network.h log.cpp log.h
dialog.cpp中include了network.h和log.h
network.h中也include了log.h
这样dialog.cpp中实际上引入了两次log.h。
在编译的时候,编译器会因为log.h中的函数被定义了两次而报错。
使用ifndef就会避免这个问题。
如果用VC编译器,也可以不使用ifndef,改用#pragma once预编译指令就可以了。
例如一个程序中包含如下文件:dialog.cpp dialog.h network.cpp network.h log.cpp log.h
dialog.cpp中include了network.h和log.h
network.h中也include了log.h
这样dialog.cpp中实际上引入了两次log.h。
在编译的时候,编译器会因为log.h中的函数被定义了两次而报错。
使用ifndef就会避免这个问题。
如果用VC编译器,也可以不使用ifndef,改用#pragma once预编译指令就可以了。
展开全部
使用ifndef的头文件都是这样写的:
xxx.h:
#ifndef XXX_H /*如果没有定义XXX_H*/
#define XXX_H /*定义XXX_H为空字符串*/
class Xxx{
//... ...
};
#endif /*结束判断*/
如果这样的话,多次引入xxx.h会像下面这样:
#include "xxx.h" /*1次引入*/
#include "xxx.h" /*2次引入*/
#include "xxx.h" /*3次引入*/
展开为:
#ifndef XXX_H /* 没有定义XXX_H,条件成立 */
#define XXX_H /*定义XXX_H为空字符串*/
class Xxx{ /*引入class Xxx*/
//... ...
};
#endif /*结束判断*/
#ifndef XXX_H /* 已经定义XXX_H,条件不成立 */
#define XXX_H /*跳过*/
class Xxx{
//... ...
};
#endif
#ifndef XXX_H /* 已经定义XXX_H,条件不成立 */
#define XXX_H /*跳过*/
class Xxx{
//... ...
};
#endif
xxx.h:
#ifndef XXX_H /*如果没有定义XXX_H*/
#define XXX_H /*定义XXX_H为空字符串*/
class Xxx{
//... ...
};
#endif /*结束判断*/
如果这样的话,多次引入xxx.h会像下面这样:
#include "xxx.h" /*1次引入*/
#include "xxx.h" /*2次引入*/
#include "xxx.h" /*3次引入*/
展开为:
#ifndef XXX_H /* 没有定义XXX_H,条件成立 */
#define XXX_H /*定义XXX_H为空字符串*/
class Xxx{ /*引入class Xxx*/
//... ...
};
#endif /*结束判断*/
#ifndef XXX_H /* 已经定义XXX_H,条件不成立 */
#define XXX_H /*跳过*/
class Xxx{
//... ...
};
#endif
#ifndef XXX_H /* 已经定义XXX_H,条件不成立 */
#define XXX_H /*跳过*/
class Xxx{
//... ...
};
#endif
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询