为什么我的类构造函数不初始化其成员变量?
Why isn't my class constructor initializing its member variables?
如果信息有点缺乏,请原谅我,因为我正在努力遵循推荐的"询问指南"。
我创建了一个名为"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引用。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 将包含C样式数组的对象初始化为成员变量(C++)
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 在循环中按顺序遍历成员变量
- c++类声明时,相同的例程,不同的成员变量类型
- 如何从另一个文件继承私有成员变量和公共函数
- 在C++类中,是否必须初始化作为数组的成员变量
- 如何从子成员函数修改父公共成员变量
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 从私有成员变量的成员方法返回unique_ptr
- 在派生类中使用基类的私有成员变量的最佳方法
- 静态 constexpr 类成员变量对多线程读取是否安全?
- C++:是否可以使用非静态成员变量模板?
- 打印所有继承的类成员变量和方法
- 如何在复杂继承中访问静态成员变量
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 成员变量与函数概念检查