问题
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#.
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);
which indeed is immutable, meaning 'const'.
Why?
CLocation
furthermore has a function
System::Drawing::Point CLocation::ToPoint ()
{
return System::Drawing::Point (x_int, y_int);
}
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.
Is this correct?
Is there a way to run this member function on a const CLocation
?
回答1:
You must indicate to the compiler that your function doesn't change the object by adding const
after the argument list.
Your function may then be called on a const
variable, but may not modify its fields.
Pay also attention that some keywords (including const
and struct
) have different meanings in C# and C++ (and other languages based on C).
Update
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).
来源:https://stackoverflow.com/questions/39560963/why-can-i-declare-const-structures-in-c-cli-but-not-in-c