[英]C++ Struct with default argument, optionally changeable in constructor
假设我有以下结构。
struct vehicle
{
int price;
char* year;
char* type;
}
我想为它创建一个常规构造函数,这将允许我指定每个成员。
尽管如此,我想将成员“type”默认设置为“car”,只需在构造函数中指定“type”,在车辆不是“car”的情况下,这种情况并不常见。
首先,您没有说出来,但我感觉到一个小误解:结构和 class 之间的区别只是约定。 结构是 C++ 中的类。 关键字struct
和class
可用于声明 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.