c++ typedef和#define的作用范围
2017-09-19 20:08
274 查看
typedef:
如果放在所有函数之外,它的作用域就是从它定义开始直到文件尾;
如果放在某个函数内,定义域就是从定义开始直到该函数结尾;
#define:
不管是在某个函数内,还是在所有函数之外,作用域都是从定义开始直到整个文件结尾。
define在同一编译单元内部,就算在不同的命名空间内,其作用范围不变。也就是从定义处一直到文件介绍。
看下面这个例子:
Main.cpp
test1.h
test1.cpp
最后结果:
如果放在所有函数之外,它的作用域就是从它定义开始直到文件尾;
如果放在某个函数内,定义域就是从定义开始直到该函数结尾;
#define:
不管是在某个函数内,还是在所有函数之外,作用域都是从定义开始直到整个文件结尾。
define在同一编译单元内部,就算在不同的命名空间内,其作用范围不变。也就是从定义处一直到文件介绍。
看下面这个例子:
Main.cpp
/** * @file Main.cpp * @author chenjiashou(chenjiashou@baidu.com) * @date 2017/09/19 17:37:33 * @version $Revision$ * @brief * **/ #include <iostream> #include "test1.h" #define LL 2 typedef 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_H void 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 <iostream> #define SS 1 void 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 define OTHER define SS define
相关文章推荐
- typedef和#define的作用范围
- 浅谈C/C++中的typedef和#define
- C++中 #ifndef #define #endif的作用
- c++中的变量作用范围
- C++中typedef和#define简介
- 浅淡C/C++中的typedef和#define
- C&C++中,typedef与#define
- 详解C/C++中的typedef和#define
- 如何区别c/c++中的#typedef 和 #define的区别
- C/C++:typedef、#define和const
- C++ typedef typename 作用
- C++:关于#define、typedef、using
- C++头文件中加#ifndef #define #endif的作用浅析
- C++ typedef 和 #define
- C/C++中的typedef和#define详解
- [c++]通过一个简单的程序引出#define与typedef的区别
- C/C++ 变量作用范围
- C/C++语法知识:typedef struct 用法 作用
- C++ typedef typename 作用
- C++ typedef用法及与#define的区别