For C #, a class can have member variables, member functions, and attributes, whereas in C + + there is no concept of "attribute". To achieve the same effect, the get_xxx () and set_xxx () Two functions are generally used in C + + to implement external access to member variables. The disadvantage of doing so is that there are a lot more redundant code in the declaration of the class:
private:
int m_data;
public:
int get_data() const;
int set_data(int value);
In order to define a data property, you need to write a lot of code, in fact, we want to program the above code, then the macro can be implemented:
#define AUTO_PROPERTY(type, name) \
private: type m_##name; \
public: type get_##name() const {return m_##name;} \
public: type set_##name(const type &value) \
{return m_##name, m_##name = value;}
然后我们就可以简化代码,增加可读性:
class class1
{
AUTO_PROPERTY(int, data)
};
This enables the addition of a property named data to the Class1, while providing basic access control functions Get_data () and Set_data (). Of course, what this macro does is simply simplifying the code and increasing readability without providing a completely new "property" pattern. If you want to customize the Get_data () or Set_data () function, this macro is not enough, so I'll give you a few more macros to achieve the effect of customizing the Get,set function:
#define PROPERTY(type, name) \
private: type m_##name; \
public: type get_##name() const; \
public: type set_##name(const type &value);
#define PROPERTY_GET(classname, type, name) \
type classname::get_##name() const
#define PROPERTY_SET(classname, type, name) \
type classname::set_##name(const type &value)
Use examples:
class myclass
{
public:
PROPERTY(int, data)
};
PROPERTY_GET(myclass, int, data)
{
return m_data;
}
PROPERTY_SET(myclass, int, data)
{
return m_data = value;
}
Of course, this is just a simple method that I provide, a brief comment, welcome advice.