简介
编程IDE:VS2013
操作系统:window 7 x64
版权所有:_ OE _, 转载请注明出处:http://blog.csdn.net/csnd_ayo
作用介绍
#
在宏中,这个符号是作用是获取参数变量名。
示例:
#include <iostream> #define printf(param) std::cout << #param << std::endl; int main(void) { int oe = 123; printf(oe); return 0; }
示例输出:
oe
解析:
打印的答案并不是预期的123,而是变量名oe,是不是有点理解他的作用了呢?
##
在宏中,他作为字符串拼接的方法。
示例:
#include <iostream> #define printf(param) std::cout << "123"###param###param << std::endl; int main(void) { int oe = 123; printf(oe); return 0; }
示例输出:
123oeoe
解析:
有些朋友可能发现,在这里我们不使用##
也可以做到拼接的效果,接下来,我们来介绍一些方法及真实的使用案例,让大家学习一下。
用法案例
我们在这里会展示未使用宏前,和使用宏后的效果。以帮助朋友们清晰的看到 #
的优势。
类内成员访问
/// 定义类中属性的访问方法
#ifndef PROPERTY_INIT
#define PROPERTY_INIT(ptype,fname,proper) \
void set##fname(ptype val)\
{\
proper = val; \
}\
ptype get##fname()\
{\
return proper; \
}
#endif
- 使用前
#include <string>
#include <iostream>
class OE {
public:
const std::string& getName(void) const {
return name_;
}
void setName(const std::string& name) {
name_ = name;
}
bool getSex(void) const {
return sex_;
}
void setSex(bool sex) {
sex_ = sex;
}
int getAge(void) const {
return age_;
}
void setAge(int age) {
age_ = age;
}
private:
int age_ = 18;
std::string name_ = "chenluyong";
bool sex_ = true;
};
int main(void) {
OE oe;
std::cout << oe.getName() << std::endl;
std::cout << oe.getSex() << std::endl;
std::cout << oe.getAge() << std::endl;
return 0;
}
- 使用后
#include <string>
#include <iostream>
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(void) {
OE oe;
std::cout << oe.getName() << std::endl;
std::cout << oe.getSex() << std::endl;
std::cout << oe.getAge() << std::endl;
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
使用案例
总结
有问题,我们通过论坛下方留言板再交流。
思考
若类内成员变量是静态的,又当如何去定义呢?