博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c++ typedef和#define的作用范围
阅读量:7240 次
发布时间:2019-06-29

本文共 1490 字,大约阅读时间需要 4 分钟。

typedef:

如果放在所有函数之外,它的作用域就是从它定义开始直到文件尾;

如果放在某个函数内,定义域就是从定义开始直到该函数结尾;

#define:

不管是在某个函数内,还是在所有函数之外,作用域都是从定义开始直到整个文件结尾。

define在同一编译单元内部,就算在不同的命名空间内,其作用范围不变。也就是从定义处一直到文件介绍。

 

看下面这个例子:

Main.cpp

/** * @file Main.cpp * @author chenjiashou(chenjiashou@baidu.com) * @date 2017/09/19 17:37:33 * @version $Revision$  * @brief  *   **/#include 
#include "test1.h"#define LL 2typedef long long ll;void test_typedef() {typedef int x_int;x_int a = 1;}namespace other {#define OTHER//不在乎是否在命名空间中//关键在一个编译单元}int main() {#ifdef LL std::cout << "LL define" << std::endl;#endif#ifdef SS std::cout << "SS define" << std::endl;#endif#ifdef OTHER std::cout << "OTHER define" << std::endl;#endif ll a = 1; print(); //x_int b = 1;//compile error return 0;}/* vim: set ts=4 sw=4 sts=4 tw=100 */

 

test1.h

/** * @file test1.h * @author chenjiashou(chenjiashou@baidu.com) * @date 2017/09/19 17:39:05 * @version $Revision$  * @brief  *   **/#ifndef TEST1_H#define TEST1_H#endif  // TEST1_Hvoid print();/* vim: set ts=4 sw=4 sts=4 tw=100 */

test1.cpp

/** * @file test1.cpp * @author chenjiashou(chenjiashou@baidu.com) * @date 2017/09/19 17:36:15 * @version $Revision$  * @brief  *   **/#include 
#define SS 1void print() {#ifdef SS std::cout << "SS define" << std::endl;#endif#ifdef LL std::cout << "LL define" << std::endl;#endif// ll c = 1; //compile error// std::cout << c << endl;}/* vim: set ts=4 sw=4 sts=4 tw=100 */

最后结果:

LL defineOTHER defineSS define

 

转载地址:http://berfm.baihongyu.com/

你可能感兴趣的文章
初始化weblogic密码
查看>>
Linux Top 命令解析
查看>>
一个C#项目 在引用References中有个引用项上有个黄色三角加感叹号 导致报错
查看>>
PPT无法修改默认打开程序的问题
查看>>
2011年度IT博客大赛50强之 jimmy_lixw
查看>>
WP8开发日志(2):MVC设计模式入门
查看>>
windows下配置Nginx1.0.9+php5.2.17
查看>>
咳咳,关于本空间的问题~
查看>>
power cpu的封装形式
查看>>
CentOS 7.2下安装Python3.5.2过程
查看>>
配置telnet客服端
查看>>
【腾讯Bugly干货分享】跨平台 ListView 性能优化
查看>>
谷歌三大核心技术(一)Google File System中文版
查看>>
体验2012 CodeRetreat全球活动
查看>>
我的友情链接
查看>>
Citrix xendesktop静态分发模式下合理管控分配虚拟桌面本地管理员权限
查看>>
解决Windows 10更新错误(Resolve Windows 10 upgrade errors)
查看>>
infortrend ESDS RAID6 数据恢复过程
查看>>
LVM逻辑卷管理器
查看>>
Plant Design Review Based on AnyCAD
查看>>