问题
Is it possible to pass a value and a constant enum to the base constructor of a class?
For example:
enum CarBrand
{
Volkswagen,
Ferrari,
Bugatti
};
class Car
{
public:
Car(int horsePower, CarBrand brand)
{
this->horsePower = horsePower;
this->brand = brand;
}
~Car() { }
private:
int horsePower;
CarBrand brand;
};
class FerrariCar : public Car
{
public:
// Why am I not allowed to do this ..?
FerrariCar(int horsePower) : Car(horsePower, CarBrand.Ferrari) { }
~FerrariCar();
};
Because I'm getting the following error when compiling something along the lines of the example: expected primary-expression before ‘.’ token
Any help would be appreciated!
回答1:
In C++, you do not prefix the enum value with the enum type name. Just say Ferrari.
回答2:
C++ enums expand its values to the surrounding scope - so in this case you can just say
FerrariCar(int horsePower) : Car(horsePower, Ferrari) { }
C++0x brings new enum classes that behave like Java enums, so you could write:
enum class CarBrand {
Volkswagen,
Ferrari,
Bugatti
};
and then use the values as CarBrand::Ferrari.
回答3:
From the docs - ISO/IEC 14882:2003(E), page 113 - point 10
The enum-name and each enumerator declared by an enum-specifier is declared in the scope that immediately contains the enum-specifier. These names obey the scope rules defined for all names in [..] and [..]. An enumerator declared in class scope can be referred to using the class member access operators (::, . (dot) and -> (arrow))
class X
{
public:
enum direction { left=’l’, right=’r’ };
int f(int i)
{ return i==left ? 0 : i==right ? 1 : 2; }
};
void g(X* p)
{
direction d; // error: direction not in scope
int i;
i = p->f(left); // error: left not in scope
i = p->f(X::right); // OK
i = p->f(p->left); // OK
// ...
}
来源:https://stackoverflow.com/questions/4639873/c-call-base-constructor-with-enum