C++/CLI: Declaring a constant array

L

longbrmb

I'm new to C++/CLI and my main background is Java. I'm trying to
create an array of constants as a static member of a class. An
example is shown below:

public ref class TestClass {
public:
static const array<constant int>^ stuff = {1,2,3,4,5};
};

This gives me compiler error C4538 which basically says that you can't
declare an array as constant. So that means that the values in my
array can't be changed, but nothing stops someone from assigning a new
array to the "stuff" variable. Am I missing something or is it not
possible to create a fixed array of constants?
 
T

Tamas Demjen

public ref class TestClass {
public:
static const array<constant int>^ stuff = {1,2,3,4,5};
};

This gives me compiler error C4538 which basically says that you can't
declare an array as constant.

Try `literal' instead of `static const'.

Tom
 
B

Ben Voigt [C++ MVP]

I'm new to C++/CLI and my main background is Java. I'm trying to
create an array of constants as a static member of a class. An
example is shown below:

public ref class TestClass {
public:
static const array<constant int>^ stuff = {1,2,3,4,5};
};

This gives me compiler error C4538 which basically says that you can't
declare an array as constant. So that means that the values in my
array can't be changed, but nothing stops someone from assigning a new
array to the "stuff" variable. Am I missing something or is it not
possible to create a fixed array of constants?

Use the "initonly" keyword. Note that "constant int" won't compile, you
probably meant "const int". In general C++/CLI support for
const-correctness is very poor.
 
L

longbrmb

Use the "initonly" keyword. Note that "constant int" won't compile, you
probably meant "const int". In general C++/CLI support for
const-correctness is very poor.

I ended up figuring that out for myself. The solution seems to work
fine for C++/CLI, but not for the .NET languages in general. I think
if you were to create a class like this and use it in C#, you would be
restricted from assigning the variable to a new array, but nothing
will stop you from modifying the values in the array itself. I
haven't actually tried this, but I have created an equivalent class in
C# and it does allow reassigning the array values. The only
difference here is that you can't specify the datatype as a "const
int" in C# because the const keyword conflicts with the readonly
keyword.

So I guess I need to come up with a better idea of how I want to
organize these constant values.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top