簡體   English   中英

如何訪問不同類中的類中的結構變量?

[英]How to access struct variables within a class, inside a different 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;
};

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

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

這是我嘗試過的幾種方法之一,嘗試做Products.price時會出錯

struct Products { ... }; 聲明類型 ,而不是產品實例

為了在您的課程中有一個實際的產品,您必須聲明一個成員變量:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM