为什么我的类构造函数不初始化其成员变量?

Why isn't my class constructor initializing its member variables?

本文关键字:成员 变量 初始化 我的 构造函数 为什么      更新时间:2023-10-16

如果信息有点缺乏,请原谅我,因为我正在努力遵循推荐的"询问指南"。

我创建了一个名为"Item"的类来存储项目信息,并定义了我的构造函数如下:

Item::Item(std::string number, std::string name, int quantity, double price) {
    itemNumber = number;
    itemName = name;
    quantity = quantity;
    unitPrice = price;
}

我在我的主函数中初始化它,如下所示:

Item temp("string", "string", 0, 0);

但当我打印item的值时,只有itemNumber和itemName打印正确。所有打印的都是随机垃圾。然后我意识到问题是数量和价格没有初始化。为什么?

尝试

this->quantity = quantity; 

或(IMHO更好):

Item::Item(const std::string& number, const std::string& name, int quantity_, double price) {
                                                          // ^
    // ...
    quantity = quantity_;
    // ...
}

或者(IMHO更好)使用构造函数初始化器列表:

Item::Item(const std::string& number, const std::string name&, int quantity, double price) 
: itemNumber(number), itemName(name), quantity(quantity), unitPrice(price) {}

"为什么?"

参数名称当前在构造函数的主体作用域中隐藏您的成员变量名称。


就我个人而言,我倾向于使用如下的类声明

class Item {
public:
    Item(const std::string& number, const std::string& name, int quantity, double price) 
    : itemNumber_(number)
    , itemName_(name)
    , quantity_(quantity)
    , unitPrice_(price) {}
private:
    std::string itemNumber_;
    std::string itemName_;
    int quantity_;
    double unitPrice_ 
};

quantity = quantity;这里两者都指参数,而不是成员变量。要引用具有相同名称参数的函数中的成员变量,必须使用this指针,例如this->quantity = quantity;,或者使用类名(例如Item::quantity = quantity; )限定它

或者使用初始化列表来避免这个问题,并可能更有效地初始化类。

Item::Item(const std::string& number, const std::string& name, int quantity, double price)
: itemNumber(number)
, itemName(name)
, quantity(quantity)
, price(price)
{
}

为了避免复制,我随意将字符串参数设置为const引用。