【问题标题】:How to use one class information in another class C++如何在另一个类 C++ 中使用一个类信息
【发布时间】:2020-05-04 00:01:03
【问题描述】:

我是 C++ 的初学者,只是想知道是否有可能我将计算放在最后一个“for”循环中,该循环使用“产品”类来计算另一个名为“价格”的类中的总额和价格。 抱歉这个奇怪的问题,我只是对如何相互使用类以及是否可以这样做感到困惑......

#include <iostream>
#include <string>
using namespace std;
class Product
{
public:
    string name;
    int amount;
    float weight;
    void get()
    {
        cout << "Give product name,amount and weight : " << endl;
        cin >> name >> amount >> weight;
    }
    void print()
    {
        cout << name << " - "<< amount<<" , " <<weight <<" kg"<< endl;
        cout << "--------" << endl;
    };
};
int main()
{
    Product p[100];
    int n;
    cout << "Give the number of products you want to get : " << endl;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        p[i].get();

    }
    cout << "Product display: " << endl;
    for (int i = 0; i < n; i++)
    {
        p[i].print();
    }
    float total = 0;
    for (int i = 0; i < n; i++)
    {
        cout << "\nPrice of " << p[i].name << " " << p[i].amount * p[i].weight << " $" << endl;
        total = p[i].amount * p[i].weight + total;
    }

    cout << "\nTotal: " << total << "$" << endl;

    cin.get(); cin.get();
    return 0;
}

【问题讨论】:

  • getPrice 方法添加到类Product 会更有意义。为什么不试试呢?
  • 因为它是一个家庭作业,添加/使用另一个类不仅仅是 1 但你对有意义的部分是正确的,谢谢...

标签: c++ visual-studio class for-loop


【解决方案1】:

当你是初学者时,有这样的问题很好。有几点我想提一下。

  1. 在您的示例中,无需创建单独的类 用于计算价格。价格的计算是一个流程/方法/集合 的指令。所以价格计算的逻辑应该是 方法和那个也在同一个类中,即Product
  2. 其次,这里所有产品的总价格对于 类,即类的不同对象没有区别。所以 在这里你需要在类下创建一个static 变量,它将 携带所有产品的总价。
  3. 您可以在 Product 类中创建一个 static 函数并通过 产品数组作为参数并遍历产品以 计算总价并将其存储在静态变量中。

希望这能消除您的疑虑。

【讨论】:

  • @user12577611 当你得到一个回答你的问题或帮助你解决问题的答案时,你应该accept这个答案。
猜你喜欢
  • 2015-07-04
  • 2019-03-11
  • 1970-01-01
  • 2017-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-19
  • 2018-02-04
相关资源
最近更新 更多