如何在托管c++中使用手写的getter/setter定义属性

How to define properties with a handwritten getter/setter in managed C++?

本文关键字:getter setter 属性 定义 c++      更新时间:2023-10-16

我需要在一个托管的c++项目中使用手写的getter/setter来定义属性,这个类将在c# . net项目中可用。

  • 关于这个主题的代码项目文章推荐了__property float Volume;,它已经过时了,现在被归类为/crl:oldSyntax

  • 开放标准管理的c++扩展文章说,定义像property float Volume;这样的属性会自动生成一个支持字段,这是我不想要或不需要的。

  • 简单地定义属性,如property float Volume;编译良好的/clr,但试图添加手写的getter/setter,如float Mixer::Volume::get(){ .. }抛出Error C2084: function X already has a body

那么,定义只读或读/写属性的正确方法是什么呢?没有后备字段,并使用定制的手写getter/setter方法?

您已经自己找到了仅标头的版本。如果您想在cpp文件中实现getter和setter,语法如下:

///////////////////////
// Foo.h:
///////////////////////
ref struct Foo
{ 
    property float Volume
    {
        float get();
        private: void set(float value);
    }
private:
    float m_backingField;
}
///////////////////////
// Foo.cpp:
///////////////////////
float Foo::Volume::get()
{
    return m_backingField;
}
void Foo::Volume::set(float value)
{
    m_backingField = value;
}

编辑:一些附加信息:

  • 可以为getter和setter指定不同的访问修饰符。为了使setter私有,我修改了源代码。
  • 请注意,与c#中不同的是,如果您使用自动生成后备存储,则不可能这样做。
  • 以前被称为"c++的托管扩展",现在(从Visual Studio 2005开始)被称为c++/CLI。这不仅是一个重命名,而且是一个全新的修订。双下划线__property关键字来自托管扩展,现在已弃用。

我发现你只需要在头文件中声明一次属性,如下所示:

property float Volume {
    float get() {
        return 0;
    }
    void set(float value) {
    }
}

如果像下面这样声明属性,就会自动生成一个后备字段:

property float Volume;