博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C/C++ "#"与"##"的作用与应用
阅读量:2493 次
发布时间:2019-05-11

本文共 2407 字,大约阅读时间需要 8 分钟。

简介

编程IDE:VS2013

操作系统:window 7 x64

版权所有:_ OE _, 转载请注明出处:



作用介绍

  • #

    在宏中,这个符号是作用是获取参数变量名。

    示例:

    #include 
    #define printf(param) std::cout << #param << std::endl; int main(void) { int oe = 123; printf(oe); return 0; }

    示例输出:

    oe

    解析:

    打印的答案并不是预期的123,而是变量名oe,是不是有点理解他的作用了呢?

  • ##

    在宏中,他作为字符串拼接的方法。

    示例:

    #include 
    #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 
#include
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 
#include
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
  • 使用案例

    1

总结

有问题,我们通过论坛下方留言板再交流。

思考

若类内成员变量是静态的,又当如何去定义呢?

你可能感兴趣的文章
redis事务
查看>>
Java_基础语法之dowhile语句
查看>>
HDU 2175 汉诺塔IX
查看>>
PAT 甲级 1021 Deepest Root
查看>>
查找代码错误.java
查看>>
vc获取特殊路径(SpecialFolder)
查看>>
单例模式
查看>>
int(3)和int(11)区别
查看>>
201521123061 《Java程序设计》第十一周学习总结
查看>>
代码小思考
查看>>
Unity中的销毁方法
查看>>
ceph删除pool提示(you must first set the mon_allow_pool_delete config option to true)解决办法...
查看>>
2016-7-15(1)使用gulp构建一个项目
查看>>
CSS 设计指南(第3版) 初读笔记
查看>>
markdown学习/mou
查看>>
CentOS 搭建 LAMP服务器
查看>>
看完此文再不懂区块链算我输,用Python从零开始创建区块链
查看>>
C/S框架-WebService架构用户凭证(令牌)解决方案
查看>>
UVA 11149.Power of Matrix-矩阵快速幂倍增
查看>>
ajax post 请求415\ 400 错误
查看>>