我个人实现的C++之get和set方法,使用宏定义
发布日期:2021-06-30 18:20:50
浏览次数:3
分类:技术文章
本文共 1846 字,大约阅读时间需要 6 分钟。
本人在C++项目中经常需要用到get和set方法,但是c++并不像 java的eclipse有自动生成 get 和 set 方法。如果手写是可以,但是当属性特别多的时候会非常麻烦。。。于是决定使用宏定义方法来解决。
本人在参考了网上资料(参见文章末尾的参考文献)之后,实现了自己的版本,cplusplusgetset.h头文件如下:
#pragma once//PropertyBuilderByTypeName 用于生成类的成员变量//并生成set和get方法//variable_type为变量类型,可以是指针类型,也可以是非指针类型,例如int,int*等//type_shortname为变量类型的缩写,例如bool缩写为b,int缩写为i,double缩写为d等//method_name为方法名称//access_permission为变量的访问权限(public, protected, private)#define PropertyBuilder_ReadWrite(variable_type, type_shortname, method_name, access_permission)\access_permission:\ variable_type m_##type_shortname##method_name;\public:\ inline variable_type get##method_name(void)\ {\ return m_##type_shortname##method_name;\ }\ inline void set##method_name(variable_type v)\ {\ m_##type_shortname##method_name = v;\ }\#define PropertyBuilder_ReadOnly(variable_type, type_shortname, method_name, access_permission)\access_permission:\ variable_type m_##type_shortname##method_name;\public:\ inline variable_type get##method_name(void) const\ {\ return m_##type_shortname##method_name;\ }\#define PropertyBuilder_WriteOnly(variable_type, type_shortname, method_name, access_permission)\access_permission:\ variable_type m_##type_shortname##method_name;\public:\ inline void set##method_name(variable_type v)\ {\ m_##type_shortname##method_name = v;\ }\
使用说明:
class MyClass { public: MyClass() { m_bLookAhead = true; m_dStatus = NULL; m_iHello = 0; } ~MyClass() {} PropertyBuilder_ReadWrite(bool, b, LookAhead, protected)//bool m_bLookAhead; PropertyBuilder_ReadWrite(double*, d, Status, protected)//bool* m_pStatus; PropertyBuilder_WriteOnly(int, i, Hello, private)//int m_iHello; public: void test() { setLookAhead(true); double a = 0; setStatus(&a); setHello(5); bool r = getLookAhead(); } };
---
参考文献
转载地址:https://libaineu2004.blog.csdn.net/article/details/92433479 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
做的很好,不错不错
[***.243.131.199]2024年04月14日 12时11分56秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
攻防世界web进阶PHP2详解
2019-04-30
如何解决词达人问题(新)
2019-04-30
攻防世界web进阶区surpersqli详解
2019-04-30
攻防世界web进阶区easytornado详解
2019-04-30
攻防世界web进阶区web2详解
2019-04-30
xss-labs详解(上)1-10
2019-04-30
xss-labs详解(下)11-20
2019-04-30
攻防世界web进阶区ics-05详解
2019-04-30
攻防世界web进阶区FlatScience详解
2019-04-30
攻防世界web进阶区ics-04详解
2019-04-30
攻防世界web进阶区Cat详解
2019-04-30
攻防世界web进阶区bug详解
2019-04-30
攻防世界web进阶区ics-07详解
2019-04-30
攻防世界web进阶区unfinish详解
2019-04-30
攻防世界web进阶区i-got-id-200超详解
2019-04-30
sql注入总结学习
2019-04-30
leetcode46 全排列
2019-04-30
leetcode121 买卖股票的最佳时机
2019-04-30
leetcode 122 买卖股票的最佳时机II
2019-04-30
leetcode 309 最佳买卖股票含冷冻期
2019-04-30