c++中的宏 #define _CLASSDEF(name) class name
1 #include <iostream> 2 using namespace std; 3 #define _CLASSDEF(name) class name; \ 4 typedef name * P##name;\ 5 typedef name & R##name;\ 6 typedef name * & RP##name;\ 7 typedef const name * PC##name;\ 8 typedef const name & RC##name 9 _CLASSDEF(base); 10 class base 11 { 12 public: 13 base() 14 { 15 } 16 base(int _a) 17 { 18 a=_a; 19 } 20 int get() 21 { 22 return a; 23 } 24 void set(int _a) 25 { 26 a=_a; 27 } 28 private: 29 int a; 30 31 }; 32 33 int main(int argc, char *argv[]) 34 { 35 base b(10); 36 Pbase pb=&b; 37 Rbase rb=b; 38 rb.set(20); 39 cout<<b.get()<<endl; 40 cout<<pb->get()<<endl; 41 cout<<rb.get()<<endl; 42 43 44 return 0; 45 }
解释说明
想要理解上面的代码,先理解c++中的宏,再理解typedef
C/C++ 宏定义中#、##、#@的区别:https://www.cnblogs.com/fnlingnzb-learner/p/6823575.html
理解了宏之后,代码就很好理解了
#define _CLASSDEF(name) class name; \ typedef name * P##name;\ typedef name & R##name;\ typedef name * & RP##name;\ typedef const name * PC##name;\ typedef const name & RC##name
_CLASSDEF(base);
上面代码提前定义了类base的几种类型,分别是
base* --> Pbase
base& --> Rbase 相当于右值引用