问题描述
我已经找到了有用的答案,为什么根本不应该这样做:
第一个有一个详细的答案,我仍然必须重新阅读几次,直到完全理解为止。
第二个有一个非常简单明了的答案(就像构造函数可能会做任何事情,因此必须在编译时运行和评估。。)
但是两者都引用C#。
I already have found useful answers why it shouldn't be possible at all:
Why does C# limit the set of types that can be declared as const?
Why can't structs be declared as const?
The first one has a detailed answer, which I still have to re-read a couple of times until I fully get it.
The second one has a very easy and clear answer (like 'the constructor might do anything, so it had to be run and evaluated at compile time').
But both refer to C#.
但是,我正在使用C ++ / CLI,并且有一个
However, I am using C++/CLI and have a
value class CLocation
{
public:
double x, y, z;
CLocation ( double i_x, double i_y, double i_z) : x(i_x), y(i_y), z(i_z) {}
CLocation ( double i_all) : x(i_all), y(i_all), z(i_all) {}
...
}
在这里我可以轻松创建一个
where I can easily create a
const CLoc c_loc (1,2,3);
这确实是不可变的,意思是 const。
which indeed is immutable, meaning 'const'.
为什么?
CLocation
还有一个功能
System::Drawing::Point CLocation::ToPoint ()
{
return System::Drawing::Point (x_int, y_int);
}
在 CLocation ,但不在
const CLocation
上。我认为这来自C#的限制(从上面的链接知道),该限制很可能来自底层的IL,因此C ++ / CLI同样受到该限制的影响。
which works well on
CLocation
, but doesn't on a const CLocation
. I think this comes from the limitation in C# (known from the links above), which likely comes from the underlying IL, so C++/CLI is affected by that limitation in the same way.
这是正确的吗?
有没有办法在 const CLocation ?
推荐答案
推荐答案
您必须向编译器指示,通过添加 const
参数列表之后。
You must indicate to the compiler that your function doesn't change the object by adding
const
after the argument list.
然后可以在
const 变量,但不能修改其字段。
Your function may then be called on a
const
variable, but may not modify its fields.
请注意,某些关键字(包括
const
和 struct
)在C#和C ++(以及其他基于C的语言)中具有不同的含义。
Pay also attention that some keywords (including
const
and struct
) have different meanings in C# and C++ (and other languages based on C).
更新
由于CPP / CLI不允许在成员函数上使用
const
修饰符,因此将变量复制到非 const
以便能够调用任何成员函数(在副本上)。
As CPP/CLI doesn't allow a
const
modifier on a member function, you'll have to copy the variable to a non-const
one to be able to call any member function (on the copy).
这篇关于为什么我可以在C ++ / CLI中声明const结构,但不能在C#中声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!