# 和 ## 在宏定义(define)中经常可以看到,是预编译过程中的常用语句
- ##是一个连接符号,用于把参数连在一起
- #是“字符串化”的意思。出现在宏定义中的#是把跟在后面的参数转换成一个字符串
#define CONVERT(name) #name
#define CAT(batman, robin) batman##robin
#define make_friend(index) printf("You and %s are friends.\n", CAT(james, index));
int
main()
{
printf("You and %s are friends.\n", CONVERT(JamesXXX));
char *james001 = "fake James 001";
char *james007 = "James Bond";
char *james110 = "fake James 110";
make_friend(001);
make_friend(007);
make_friend(110);
return 0;
}
//输出
// You and JamesXXX are friends.
// You and fake James 001 are friends.
// You and James Bond are friends.
// You and fake James 110 are friends.
实际使用实例
类内成员访问
#include <string>
#include <iostream>
#ifndef PROPERTY_INIT
#define PROPERTY_INIT(ptype, fname, proper) \
void set##fname(ptype val) \
{ \
proper = val; \
} \
ptype get##fname() \
{ \
return proper; \
}
#endif
class OE
{
public:
PROPERTY_INIT(const std::string &, Name, name_)
PROPERTY_INIT(int, Age, age_)
PROPERTY_INIT(bool, Sex, sex_)
private:
int age_ = 18;
std::string name_ = "chenluyong";
bool sex_ = true;
};
int main()
{
OE oe;
oe.setAge(28);
std::cout << oe.getName() << std::endl; //chenluyong
std::cout << oe.getSex() << std::endl; //1
std::cout << oe.getAge() << std::endl; //28
return 0;
}
优雅的成员变量
// 只读属性
#ifndef PROPERTY_R
#define PROPERTY_R(xtype, xname, proper) \
private: \
void set##xname(xtype val) { proper = val; } \
\
public: \
xtype get##xname() { return proper; } \
\
private: \
xtype proper;
#endif
// 读写属性
#ifndef PROPERTY_RW
#define PROPERTY_RW(xtype, xname, proper) \
public: \
void set##xname(xtype val) { proper = val; } \
\
public: \
xtype get##xname() { return proper; } \
\
private: \
xtype proper;
#endif
class OEA
{
PROPERTY_RW(int, Age, age_);
PROPERTY_RW(std::string, Name, name_);
};
int main()
{
OEA oe;
oe.setAge(78);
oe.setName("hello");
std::cout << oe.getName() << std::endl; //hello
std::cout << oe.getAge() << std::endl; //78
return 0;
}