简体   繁体   中英

How to set the default value of enum type variable?

How to set the default value of the enum type tip, I tried setting it to 0 or 1, or nothing, but I get the same error?

enum tip {
pop,
rap,
rock
};

class Pesna{
private:
char *ime;
int vremetraenje;
tip tip1;

public:
//constructor
Pesna(char *i = "NULL", int min = 0, tip t){
    ime = new char[strlen(i) + 1];
    strcpy(ime, i);
    vremetraenje = min;
    tip1 = t;
}

};

You must set it to one of the enum values, like:

Pesna(char *i = "NULL", int min = 0, tip t = pop)
                                        // ^^^^^

Another techique is to use a Default value declared in the enum itself and use that one. This makes it easier if you change your mind later what the default should be:

enum tip {
    pop,
    rap,
    rock,
    Default = rap, // Take care not to use default, that's a keyword
};

Pesna(char *i = "NULL", int min = 0, tip t = Default)
                                        // ^^^^^^^^^

Don't think of enums as numbers like 0 or 1 (in some cases they can even be signed or unsigned). Think of them like more like a class/struct in the way that you refer to them. So using

tip = 1

wouldn't make since because 'tip' isn't a number, it's its own entity. Without explicitly stating enums start somewhere else like

enum tip { pop = 7, ...}

the first enum will start at 0. So you can cast/uncast using those representations with 'numbers', but again I would be careful with that. Also in general, it's nicer to declare class-specific enums inside the class's public namespace like

class Pesna {
  public:
    enum tip { pop, ...}

and then use the scope resolution operator to access them

Pesna::tip

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM