C++ C++;使用枚举调用基构造函数
是否可以将值和常量枚举传递给类的基构造函数 例如:C++ C++;使用枚举调用基构造函数,c++,inheritance,constructor,C++,Inheritance,Constructor,是否可以将值和常量枚举传递给类的基构造函数 例如: enum CarBrand { Volkswagen, Ferrari, Bugatti }; class Car { public: Car(int horsePower, CarBrand brand) { this->horsePower = horsePower; this->brand = brand; }
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();
};
因为我在按照示例的思路编译某些内容时遇到了以下错误:在“.”之前应该有一个主表达式
任何帮助都将不胜感激 > C++中,不使用枚举类型名称来枚举枚举值。只需说法拉利
C++枚举将其值扩展到周围的范围-因此在本例中,您可以说
FerrariCar(int horsePower) : Car(horsePower, Ferrari) { }
C++0x带来了行为类似于Java枚举的新枚举类,因此您可以编写:
enum class CarBrand {
Volkswagen,
Ferrari,
Bugatti
};
然后使用文件ISO/IEC 14882:2003(E)第113页第10点中的值作为
CarBrand::Ferrari
枚举说明符声明的枚举名称和每个枚举数在紧接着包含枚举说明符的范围内声明。这些名称遵守为[…]和[…]中的所有名称定义的范围规则。可以使用类成员访问运算符(:,(点)和->(箭头))引用类作用域中声明的枚举数
只需简单说明一下-您的
类FerrariCar
有一个大写的类
-它需要是类
。可能还需要使用构造函数初始化列表,而不是正文中的赋值
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
// ...
}