问题
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:
- Just leave the 'static const' declaration
- 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