我个人实现的C++之get和set方法,使用宏定义
发布日期:2021-06-30 18:20:50 浏览次数:2 分类:技术文章

本文共 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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:成功实现C++调用C#写的库(CLR),我的个人心得与总结
下一篇:VC++预编译头文件 – stdafx.h的作用是什么?

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月28日 01时02分15秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章