C++的类C#属性的实现

本文详细介绍了C++中__declspec(property)的用法,包括其语法、如何将数据成员操作转换为get和put函数,以及提供了一个示例和使用PROPERTY宏的高级应用。
  1. 引言

    主要包括:

语法

评论

例子

   这个属性实现主要用在非静态的虚拟数据成员上

  1. 语法:

__declspec( property( get=get_func_name ) ) declarator
   __declspec( property( put=put_func_name ) ) declarator
   __declspec( property( get=get_func_name, put=put_func_name ) ) declarator

    2.评论:

      当编译器看到这个数据成员变量时。用(.或->)就将操作转换成get或put函数。根据当时引用的时是左值还是右值。另外,这个属性对数组也是有用的,比如,下面的例子,

__declspec(property(get=GetX, put=PutX)) int x[];

  • i = p->x[a][b] 这个表达式将转换成 i = p->getX(a,b)
  • p->x[a][b] = i, 表达式将转换成 p->putX(a,b,i)

  3. 例子 

// declspec_property.cpp
struct S {
   int i;
   void putprop(int j) {
      i = j;
   }

   int getprop() {
      return i;
   }

   __declspec(property(get = getprop, put = putprop)) int the_prop;
};

int main() {
   S s;
   s.the_prop = 5;
   return s.the_prop;
}

4.运行结果:

5.进一步:

#ifndef PROPERTIES_H
#define PROPERTIES_H

#define PROPERTY(t,n)  __declspec( property ( put = property__set_##n, get = property__get_##n ) ) t n;\
    typedef t property__tmp_type_##n
#define READONLY_PROPERTY(t,n) __declspec( property (get = property__get_##n) ) t n;\
    typedef t property__tmp_type_##n
#define WRITEONLY_PROPERTY(t,n) __declspec( property (put = property__set_##n) ) t n;\
    typedef t property__tmp_type_##n

#define GET(n) property__tmp_type_##n property__get_##n()
#define SET(n) void property__set_##n(const property__tmp_type_##n& value)

#endif // PROPERTIES_H
// main.cpp
#include <iostream>

#include <math.h>

#include "properties.h"

class Vector2
{
public:
    float x;
    float y;

    READONLY_PROPERTY(float, Length);
    GET(Length)
    {
        return sqrt((x*x + y*y));
    }
};

int main()
{
    Vector2 vec;
    vec.x = 1;
    vec.y = 1;
    std::cout << "Length of vector(" << vec.x << ", " << vec.y << ") = ";
    std::cout << vec.Length << "\n"; // <--- property, not a function call

    return 0;
}

6. 参考链接:

    property (C++) | Microsoft Learn   C++ 实现 get set_c++ 实现 get set_xiaojunjun1202的博客-优快云博客

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值