[英]How to initialize static const member that is array of another class, and use it?
我正在尝试用库存实例化自动售货机。 我计划的库存是一系列 class 饮料。 这是我到目前为止所写的。
VendingMachine.h - 应该包含饮料数组 class
#include "Drinks.h"
class VendingMachine {
private:
static const int NUM_DRINKS = 5;
static const Drinks drinks[NUM_DRINKS];
public:
VendingMachine();
};
现在饮料.h
#include <string>
class Drinks {
private:
std::string name;
double price;
int qtyInMachine;
public:
Drinks(std::string name, double price, int qtyInMachine);
void decrementQuantity();
};
自动售货机.cpp
#include "VendingMachine.h"
VendingMachine::VendingMachine() {
}
饮料.cpp
#include <string>
#include "Drinks.h"
Drinks::Drinks(std::string n, double p, int qty) : name(n), price(p), qtyInMachine(qty) {
}
void Drinks::decrementQuantity() {
qtyInMachine--;
}
现在进行测试程序
#include <iostream>
#include "VendingMachine.h"
const Drinks VendingMachine::drinks[VendingMachine::NUM_DRINKS] {Drinks("Cola",1.25,20),
Drinks("Root Beer",1.35,20),Drinks("Orange Soda",1.20,20),Drinks("Grape Soda",1.20,20),
Drinks("Bottled Water",1.55,20)};
int main() {
VendingMachine vm1;
for (int i = 0; i < VendingMachine::NUM_DRINKS; i++) {
std::cout << vm1.drinks[i].name << " ";
}
}
我定义饮料编译器的行抱怨它不是一个完整的 const 表达式,并且 VendingMachine::NUM_DRINKS 在上下文中是私有的。 它为我的带有 NUM_DRINKS 的 for 语句声明了相同的私有上下文错误,在我的 cout 声明中它声称对于饮料和名称都相同。 我需要知道如何以及在何处初始化饮料以及如何在 main 中使用而不会出现“在此上下文中私有”错误。
由于我是一般的课程和 OO 的极端初学者,我找不到我的错误。 非常感谢任何帮助。
实际上,您需要研究/修改 OOP 的封装和数据隐藏概念以及访问说明符( private
和public
)的 C++ 的特定功能以及它们的使用方式和上下文。
注意:还有一个protected
的访问说明符,您可以在 inheritance 主题中研究它。
public
部分对外界可见,例如其他类、函数等。private
只能在 class 本身内访问。 您有在public
环境中访问的私有成员,这就是您收到这些错误的原因,即:
class VendingMachine {
private:
static const int NUM_DRINKS = 5; // private to class
static const Drinks drinks[NUM_DRINKS]; // private to class
public:
VendingMachine(){}
};
并且,在main
function 中:
int main() {
VendingMachine vm1;
for (int i = 0; i < VendingMachine::NUM_DRINKS; i++) { // accessing private member VendingMachine::NUM_DRINKS
std::cout << vm1.drinks[i].name << " "; // accessing private members vm1.drinks[i].name
}
}
name
数据成员是 Drinks class private
的,您在main
中公开访问它。
这些是您需要解决的问题。
为了访问私有数据成员,通常使用访问器 function 来访问name
,您将有一个公共getName()
方法等等。
private
static
数据成员或 class 成员,您需要public
static
成员函数。我想指出的另一件事是:
// Declaration: Observe names of the method arguments
Drinks(std::string name, double price, int qtyInMachine);
// Definition: Observe the names of the arguments here
Drinks::Drinks(std::string n, double p, int qty) : name(n), price(p), qtyInMachine(qty) {
}
在像现在这样的单独的接口/实现场景中,这并不重要。 但是,如果您稍后需要移动 class 中的定义,则必须使它们保持一致。 因此,从长远来看,这是一种维护开销。
这是一个最小修改的工作示例: http://ideone.com/tr5oZu
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.