简体   繁体   English

C++ 带有默认参数的结构,可以在构造函数中更改

[英]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".尽管如此,我想将成员“type”默认设置为“car”,只需在构造函数中指定“type”,在车辆不是“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.首先,您没有说出来,但我感觉到一个小误解:结构和 class 之间的区别只是约定。 Structs are classes in C++.结构是 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).关键字structclass可用于声明 class ,唯一的区别是默认访问(根据结构具有所有公共的通用约定)。

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):顺便说一句,您可以简单地编写两个构造函数(我将std::string用于字符串,因为我发现 c-strings 非常难以使用):

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):您还可以在 class 初始化程序中使用(它们随 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.构造函数上的初始化列表胜过 in class 初始化,在第二个构造函数中使用了 in class 初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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