C ++ Constructor of enumerated call base

Is it possible to pass the value and constant enum to the base constructor of the class?

For instance:

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 get the following error when compiling something line by line in the example: expected primary-expression before ‘.’ token

Any help would be appreciated!

+3
source share
3 answers

In C ++, you are not a prefix value of an enumeration with an enumeration type name. Just say it Ferrari.

+10

C ++ enumerations extend their values ​​to the surrounding area - so in this case you can simply say

FerrariCar(int horsePower) : Car(horsePower, Ferrari) { }

C ++ 0x contains new enum classes that behave like Java enums, so you can write:

enum class CarBrand {
   Volkswagen,
   Ferrari,
   Bugatti
};

and then use values ​​like CarBrand::Ferrari.

+4

- ISO/IEC 14882: 2003 (E), . 113 - 10

The enumeration name and each enumerator declared by the enumeration qualifier are declared in the area that immediately contains the enumeration qualifier. These names obey the scope rules defined for all names in [..] and [..]. An enumerator declared in a class scope may refer to the use of access operators for class members (::,. (Point) 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
    // ...
}
0
source

Source: https://habr.com/ru/post/1784377/


All Articles