一、#define
#define在预编译时宏替换,容易出错,那么有什么方法可以改善呢?答案肯定时有,我们从替换类型、替换常量、替换表达式三个方面分析。
- 类型
#define pchar char* 不太用
typedef char pchar;* C语言
using pchar=char;* C++ - 常量
#define SIZE 10; C语言
const int SIZE = 10; C++,因为C语言中SIZE是常变量 - 表达式/函数
int sum(int a, int b) {return a+b;}
#define sum(a,b) a+b C语言
inline int sum(int a, int b) {return a+b;} C++
二、代码
#include<iostream>
using namespace std;
//类型
#define pchar1 char*
typedef char* pchar2;
using pchar3 = char*;
//变量
#define SIZE1 10
const int SIZE2 = 10;
//表达式/函数
#define Sum1(a,b) a+b
int Sum2(int a, int b)
{
return a + b;
}
inline int Sum3(int a, int b)
{
return a + b;
}
int main()
{
char ch = 'a';
pchar1 p1 = &ch;
pchar2 p2 = &ch;
pchar3 p3 = &ch;
cout << *p1 << " " << *p2 << " " << *p3 << endl;
cout << SIZE1 << " " << SIZE2 << endl;
cout << Sum1(1, 2) << " " << Sum2(1, 2) << " " << Sum3(1, 2) << endl;
return 0;
}