C++ Call base constructor with enum

好久不见. 提交于 2020-01-04 03:15:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!