[英]How to access struct variables within a class, inside a different class?
I have multiple files for each class. 我每个班级都有多个文件。 I'm trying to use data from a struct (inside the first class) and use it in the second class.
我正在尝试使用来自结构的数据(在第一类内部),并在第二类中使用它。
I've tried putting the struct in its own file, but this felt a bit unnecessary. 我尝试将结构放入其自己的文件中,但这感觉有点不必要。 I've tried a few different ways of coding it out, such as declaring the struct in main and also declaring the struct in the other class.
我尝试了几种不同的编码方式,例如在main中声明该结构,并在另一个类中声明该结构。
// class 1
class Shop
{
public:
struct Products
{
int price;
int quantity;
};
void SetProductValue();
private:
float register_total;
};
// class 2:
class Consumer
{
public:
Shop Products;
int total_customers;
bool buy_product(); // <--
for this?
private:
string consumer_name;
float Consumer_balance;
};
What does the function description look like for void buy_product()? void buy_product()的功能描述是什么样的?
bool Consumer::buy_product();
{
if (consumer_balance < Products.price) return false;
if (consumer_balance >= Products.price) return true;
}
This is one of several ways I've tried, and I get errors for trying to do Products.price 这是我尝试过的几种方法之一,尝试做Products.price时会出错
struct Products { ... };
declares a type , not a product instance . 声明类型 ,而不是产品实例 。
In order to have an actual product in your class, you have to declare a member variable: 为了在您的课程中有一个实际的产品,您必须声明一个成员变量:
class Shop
{
public:
struct Product // no need for "s"
{
int price;
int quantity;
};
void SetProductValue();
private:
// either:
Product product; // <--- HERE
// or, if your shop has multiple products:
std::vector<Product> products;
float register_total;
};
In order to access one specific product (which one?), your Shop
class has to expose some accessor functions. 为了访问一个特定的产品(哪个?),您的
Shop
类必须公开一些访问器功能。 An option is to select a product by name: 一种选择是按名称选择产品:
Product Shop::GetProductByName(const std::string& name) const
{
// find right product _instance_ here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.