C++/CLI — Access Structure Member

人走茶凉 提交于 2019-12-25 02:31:53

问题


I am trying to access a .NET structure member but compilation fails even for this simple example:

.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;
  // .....
}

The statement which assigns the MinimumSize.Width to the local variable i fails to compile:

  • "No instance of function "System::Drawing::Size::Width::get()" matches the argument list and object (the object has type qualifiers that prevent a match) object type is const System::Drawing::Size

The assignment compiles without error when I remove the "const" in the declaration but I want to keep the value public and read-only.

Can somebody give me a hint how to specify that?


回答1:


I have just tried it: 'initonly' produces two messages when I attempt to allocate MinimumSize.Width to 'i':

  • Warning C4395 'System::Drawing::Size::Width::get': member function will be invoked on a copy of the initonly data member 'MBcppLibrary::DrForm::MinimumSize' (as mentioned by Dmitry Nogin / Hans Passant)

plus the message

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

I am using this solution:

  1. Just leave the 'static const' declaration
  2. Apply a type cast to the assignment statement
int i = (( System::Drawing::Size)MinimumSize).Width;

This cast gets rid of the 'const', compiles without any error/warning and executes as expected. Or is this a bit too much brut force?

Regards PaulTheHacker



来源:https://stackoverflow.com/questions/52137406/c-cli-access-structure-member

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!