Home > Software engineering >  Why calling constructor with enum argument failed while using it as class field?
Why calling constructor with enum argument failed while using it as class field?

Time:01-15

I wrote a simple class constructor with one argument of enum type.

enum Kind {
    One,
    Two
};
class KindClass {
private:
    Kind fKind;

public:
    explicit KindClass(Kind kind) : fKind(kind) {}
};

Then make a global constant of it and it work.

static const KindClass globalKindClass(One);

But when making const field of it compile failed with error : "error: ‘One’ is not a type"

class UserClass {
private:
    static const KindClass kindClass(One);
};

What's the problem ? And how to solve it ?

https://godbolt.org/z/Yn45objnd

CodePudding user response:

Use curly braces and constexpr to fix it:

class KindClass {
private:
    Kind fKind;

public:
    explicit constexpr KindClass(Kind kind) : fKind(kind) {}
};

class UserClass {
private:
    static constexpr KindClass kindClass{One};
};
  • Related