如何在另一类C ++中使用一个类信息

问题描述 投票:0回答:1

我是C ++的初学者,只是想知道如果有可能,我可以将计算结果放在最后一个“ for”循环中,该循环使用“ Product”类中的名称,数量和重量在另一个名为“价格”的类中计算总价和价格。对不起这个奇怪的问题,我只是很困惑如何相互使用类,如果可以的话...

#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;
}
c++ visual-studio class for-loop
1个回答
0
投票

初学者时有这样的问题很好。我只想提几点。

  1. 在您的示例中,无需创建单独的类用于计算价格。价格的计算是一种流程/方法/设置指令。因此,计算价格的逻辑应该是方法,也属于同一类,即Product
  2. 其次,所有产品的总价对于该类,即该类的不同对象没有什么不同。所以在这里,您需要在该类下创建一个static变量包含所有产品的总价。
  3. 您可以只在Product类中创建一个static函数并通过产品数组作为参数,并循环遍历产品计算总价格并将其存储在静态变量中。

希望这消除了您的疑问。

© www.soinside.com 2019 - 2024. All rights reserved.