如何在类别内的类中访问类中的结构变量

How to access struct variables within a class, inside a different class?

本文关键字:访问 结构 变量      更新时间:2023-10-16

我每个类都有多个文件。我正在尝试使用来自结构的数据(在第一类内部(并在第二类中使用。

我尝试将结构放在自己的文件中,但这感觉有些不必要。我已经尝试了几种编码方式,例如在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;
};

void buy_product((的功能描述是什么样的?

bool Consumer::buy_product();
{
  if (consumer_balance < Products.price) return false;
  if (consumer_balance >= Products.price) return true;
}

这是我尝试过的几种方法之一,我会因尝试使用产品而遇到错误。

struct Products { ... };声明 type ,而不是产品实例

为了在您的班级中拥有实际产品,您必须声明成员变量:

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; 
};

为了访问一个特定产品(哪一种?(,您的Shop类必须揭示某些访问器功能。一个选项是按名称选择产品:

Product Shop::GetProductByName(const std::string& name) const
{
    // find right product _instance_ here
}