如何在托管c++中使用手写的getter/setter定义属性
How to define properties with a handwritten getter/setter in managed C++?
我需要在一个托管的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;
相关文章:
- 如何为 C 型字符串数组编写 getter 和 setter?
- 有没有办法在没有括号的情况下在C++中调用成员的getter/setter?
- Boost python getter/setter with the same name
- 如何为数组成员变量声明 getter/setter
- 具有多行字符串宏观的Getter/Setter生成
- 专用对象"getter setter"特定对象
- 具有相同名称的Getter/Setter
- C++ 中 getter setter 和构造函数之间的视觉差异
- C++中的getter/setter是正确的方法
- 绑定C++成员变量:getter/setter 或原始指针
- C++getter/setter、互斥、细粒度锁定
- Getter & Setter 的最佳性能
- 如何在公共 API 接口类中将 auto getter&setter 与 PIMPL 设计模式相结合
- 混合getter /setter和普通变量
- 如何重构冗余的getter/setter方法
- 如何在托管c++中使用手写的getter/setter定义属性
- C++ getter/setter paradigm
- C++ Getter/Setter (Alternatives?)
- 使用值包装器和 operator() 重载来简化 getter/setter 设计:这是一种危险的做法
- c++中堆对象getter / setter的更好实践