Forgive me if the information is a bit lacking as I am trying to follow the recommended "Asking Guidelines".
I have created a class called "Item" to store item information and have defined my constructor as follows:
Item::Item(std::string number, std::string name, int quantity, double price) {
itemNumber = number;
itemName = name;
quantity = quantity;
unitPrice = price;
}
and I initialize it in my main function like so:
Item temp("string", "string", 0, 0);
but when I printed the values of item, only itemNumber and itemName printed correctly.all that printed was random garbage. Then I realized the issue is quantity and price aren't getting initialized. Why is that?
Try
this->quantity = quantity;
or (IMHO better):
Item::Item(const std::string& number, const std::string& name, int quantity_, double price) {
// ^
// ...
quantity = quantity_;
// ...
}
or (IMHO even better) use a constructor initializer list:
Item::Item(const std::string& number, const std::string name&, int quantity, double price)
: itemNumber(number), itemName(name), quantity(quantity), unitPrice(price) {}
" Why is that?"
The parameter name currently shadows your member variable name in the constructor's body scope.
Personally I tend to have class declarations like follows
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_
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句