简体   繁体   中英

C++ Struct with default argument, optionally changeable in constructor

Let's say I have the following struct.

struct vehicle
{
  int    price;                           
  char*  year;                           
  char*  type; 
}

I would like to make a regular constructor for it, that would allow me to specify each member.

Nevertheless, I would like to set the member "type", as "car" by default, having only to specify the "type" in the constructor, in the not so often cases when the vehicle would not be a "car".

First of all, you didn't say it, but I sense a small misunderstanding: The difference between a struct and a class is just convention. Structs are classes in C++. The keywords struct and class can be used to declare a class and the only difference is the default access (in accordance with the common convention that structs have all public).

That out of the way, you can simply write two constructors (i am using std::string for strings, because I find c-strings extremely difficult to work with):

struct vehicle
{
  int price;                           
  std::string year;                           
  std::string type; 
  vehicle(int p, const std::string& y, const std::string& t) : price(p),year(y),type(t) {}
  vehicle(int p, const std::string& y) : price(p),year(y),type("car") {}
};

You can also use in class initializer (they came with C++11):

struct vehicle
{
  int price;                           
  std::string year;                           
  std::string type{"car"}; 
  vehicle(int p, const std::string& y, const std::string& t) : price(p),year(y),type(t) {}
  vehicle(int p, const std::string& y) : price(p),year(y) {}
};

The initializer list on the constructor wins over the in class initializer, and in the second constructor the in class initializer is used.

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