C ++ / CLI-访问结构成员 [英] C++/CLI -- Access Structure Member
问题描述
我正在尝试访问.NET结构成员,但即使对于这个简单的示例,编译也会失败:
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;
// .....
}
我无法编译到局部变量的MinimumSize.Width:
The statement which assigns the MinimumSize.Width to the local variable i fails to compile:
- 没有函数实例 System :: Drawing :: Size :: Width :: get()匹配参数列表和对象(该对象具有防止匹配的类型限定符),对象类型为const System :: Drawing :: Size
当我删除声明中的 const但我希望保持该值公开且只读时,赋值编译没有错误。
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?
推荐答案
我刚刚尝试过:'initonly'产生两个消息,当我尝试将MinimumSize.Width分配给'i':
I have just tried it: 'initonly' produces two messages when I attempt to allocate MinimumSize.Width to 'i':
- 警告C4395'System :: Drawing :: Size :: Width :: get':成员函数将在initonly数据成员'MBcppLibrary :: DrForm :: MinimumSize'(
德米特里·诺金(Dmitry Nogin) /汉斯·帕桑(Hans Passant)提到的
- 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)
加上消息
- 不允许使用initonly字段的地址
我正在使用此解决方案:
I am using this solution:
- 只需保留'static const'声明
- 将类型转换应用到赋值语句
int i = (( System::Drawing::Size)MinimumSize).Width;
此强制类型转换摆脱了'const',无需任何编译即可错误/警告,并按预期执行。还是这有点过分暴力?
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?
关于PaulTheHacker
Regards PaulTheHacker
这篇关于C ++ / CLI-访问结构成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!