C + + implementation automatically adds a "property" access code to an object

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.