簡體   English   中英

C++ 帶有默認參數的結構,可以在構造函數中更改

[英]C++ Struct with default argument, optionally changeable in constructor

假設我有以下結構。

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

我想為它創建一個常規構造函數,這將允許我指定每個成員。

盡管如此,我想將成員“type”默認設置為“car”,只需在構造函數中指定“type”,在車輛不是“car”的情況下,這種情況並不常見。

首先,您沒有說出來,但我感覺到一個小誤解:結構和 class 之間的區別只是約定。 結構是 C++ 中的類。 關鍵字structclass可用於聲明 class ,唯一的區別是默認訪問(根據結構具有所有公共的通用約定)。

順便說一句,您可以簡單地編寫兩個構造函數(我將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") {}
};

您還可以在 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) {}
};

構造函數上的初始化列表勝過 in class 初始化,在第二個構造函數中使用了 in class 初始化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM