Reputation: 3
I'm a beginner in C++ so I'm sorry if this is super obvious, but I have an issue with assigning values to an enum. I've declared the enum like so in a header file:
enum face
{ paramControlHeight = 40,
paramLabelWidth = 80,
paramSliderWidth = 300
};
And tried assigning an integer. Needless to say it doesn't work:
paramControlHeight = 40;//Not assignable
After googling about for a while, I tried:
using type_of_p=decltype(paramControlHeight);
Which as I understand, should yield the type of paramControlHeight, and enable me to use
paramControlHeight=static_cast<type_of_p> (40);
But I get the same "un-assignable" error
If anyone could point me in the right direction I'd be very grateful
Upvotes: 0
Views: 74
Reputation: 122458
I want to assign "paramControlHeight" which is inside my enum a different value. So, for example, it starts out as 40, but I would like to change it to 80 later on
You seem to misunderstand what enums are. You seem to expect the enum to behave like this
struct face
{ int paramControlHeight = 40;
int paramLabelWidth = 80;
int paramSliderWidth = 300;
};
face f; // create instance
f.paramControlHeight = 40; // modify member
However, an enum is rather like a
struct face
{
static const int paramControlHeight = 40;
static const int paramLabelWidth = 80;
static const int paramSliderWidth = 300;
};
Now back to your actual enum:
enum face
{ paramControlHeight = 40,
paramLabelWidth = 80,
paramSliderWidth = 300
};
Here paramControlHeight
is an enumerator with the value 40
. You cannot modify it. It is not meant to be modified. It is meant to enumerate. What you can do is:
face f{ paramControlHeight }; // create instance of face
f = paramSliderWidth; // assign a different value to it
A more typical enum would be
enum face_parts {
nose = 1,
eye = 2,
mouth = 3
};
That you could use like this
void print_face_part( face_parts fp ){
if (fp == nose) std::cout << "nose";
if (fp == eye) std::cout << "eye";
if (fp == mouth) std::cout << "mouth";
}
In simple terms an enum lets you name and group constants. Note that since C++11 there are scoped enums that are more flexible and dont introduce the name of the enumerators in the enclosing namespace.
Upvotes: 2
Reputation: 29975
paramControlHeight
, paramLabelWidth
, paramSliderWidth
are the values. You can't assign anything to them more than you can assign a value to 42
.
Upvotes: 1