C++/CLI -- 访问结构成员

C++/CLI -- Access Structure Member

我正在尝试访问 .NET 结构成员,但即使对于这个简单的示例,编译也会失败:

.h:

using namespace System::Drawing;
namespace MyNamespace{
  public ref class MyClass{
    public:
      MyClass();
      static const System::Drawing::Size MinimumSize = System::Drawing::Size(20,20);
  }
}

.cpp:

#include "MyInclude.h"
MyClass::MyClass(){
  int i = MinimumSize.Width;
  // .....
}

将MinimumSize.Width赋值给局部变量i的语句编译失败:

当我删除声明中的 "const" 但我想保留值 public 和只读时,赋值编译没有错误。

有人可以提示我如何指定吗?

我刚刚尝试过:当我尝试将 MinimumSize.Width 分配给 'i' 时,'initonly' 产生 两条 消息:

  • 警告 C4395 'System::Drawing::Size::Width::get':将在 initonly 数据成员的副本上调用成员函数 'MBcppLibrary::DrForm::MinimumSize'( 如 德米特里·诺金 / 汉斯·帕桑特)

加留言

  • "taking the address of an initonly field is not allowed"

我正在使用这个解决方案:

  1. 只留下'static const'声明
  2. 对赋值语句应用类型转换
int i = (( System::Drawing::Size)MinimumSize).Width;

此转换摆脱了 'const',编译时没有任何 error/warning 并按预期执行。还是这有点太暴力了?

问候 PaulTheHacker