简体   繁体   中英

How to use one class information in another class C++

i'm a beginner in C++ and just wanted to know if it is possible for me to put the calculation in the last "for" loop that uses the name,amount and weight from the "Product" class to calculate the total and price in another class that would be titled "Price". Sorry for the weird question i am just confused as to how to use classes with one another and if it is possible to do so...

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

Its fine to have such questions when you are a beginner. There are few points I would to mention.

  1. In your example there is no need of creating a separate class just for calculating the price. Calculation of price is a flow/method/set of instructions. So the logic of calculation of price should be a method and that too in the same class ie Product .
  2. Secondly here the total price for for all the products is common for the class ie it is not different for different objects of the class. So here you need to create a static variable under the class which will carry the total price of all the products.
  3. You can just create a static function in the Product class and pass the array of product as an argument and loop through the products to calculate the total price and store it in the static variable.

Hope this clears your doubt.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM