Reputation: 1602
I think this is more a stylistic question, but I have a class with an enum for statistic distribution type (that is only used in this class):
Entity {
public:
enum DistributionType {NORM, UNIFORM_INT, UNIFORM_SPECIFIED, BINOMIAL };
distributionType ds;
...
}
I want to make a DistributionType value as a parameter for my constructor:
Entity salesVolume = new Entity(Entity::DistributionType.NORM);
but this doesn't work (I guess it expects DistributionType when it's being passed an int value?)
What is the right way to call a constructor with an enum value that is part of that same class? I could do it by typecasting to int, but this doesn't seem very tight. I could also exclude the enum from the class and define it separately (which I've seen) - is that a more common way to do it?
Thanks guys
Upvotes: 0
Views: 157
Reputation: 28913
You can refer to it either as Entity::NORM
or, more explicitly (in C++11), Entity::DistributionType::Norm
.
However, on a stylistic note, this isn't Java. The code you showed will be slower and likely leak memory than just using the natural way of coding in C++, using automatic variables (variables created "on the stack"). Your code also won't compile because new
gives you a pointer to the object. However, Instead of
Entity * salesVolume = new Entity(Entity::NORM);
Prefer
Entity salesVolume(Entity::NORM);
Upvotes: 1
Reputation: 121
Can you please what error are you getting, since this code should work, Only problems are that :
Entity *salesVolume = new Entity(Entity::Entity.NORM);
Please Note the "*" before sa;esVolume. ie you have to declare it as pointer.
Upvotes: 0
Reputation: 227618
With enums, there is no "namespace", so you need this:
Entity* salesVolume = new Entity(Entity::NORM);
C++11 provides "enum classes" or "strongly typed enums" to solve this weirdness. It also allows you to use the enum name as a "scope" for traditional enums, so you could do this too:
Entity* salesVolume = new Entity(Entity::DistributionType::NORM); // C++11 only
Upvotes: 1