c++ - 如何在另一个类 C++ 中使用一个类信息
问题描述
我是 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;
}
解决方案
当你是初学者时,有这样的问题很好。有几点我想提一下。
- 在您的示例中,无需创建单独的类来计算价格。价格计算是一个流程/方法/一组指令。所以价格计算的逻辑应该是一个方法,并且也是在同一个类中,即
Product
。 - 其次,这里所有产品的总价格对于该类是通用的,即对于该类的不同对象没有不同。所以在这里你需要
static
在类下创建一个变量,它将携带所有产品的总价格。 - 您可以
static
在 Product 类中创建一个函数,并将产品数组作为参数传递并循环遍历产品以计算总价格并将其存储在静态变量中。
希望这可以消除您的疑问。
推荐阅读
- reactjs - ts2339) 类型“{}”上不存在属性电话
- cuda - CUDA 应用程序之间的同步
- php - Symfony 5 中奇怪的循环依赖
- python - 为什么 pyspark/serializers.py 不释放内存?
- c - GCC 是编译器还是编译过程的工具集合?
- amazon-web-services - 如何理解 AWS CloudTrail 成本
- flutter - 在flutterwith pushNamed中在屏幕之间传递图像
- owl-carousel-2 - 猫头鹰轮播自动播放超时不起作用
- javascript - 由于内存泄漏,我无法在 heroku 中部署我的应用程序。connect.session()
- c# - 试图将 xmlNodeList 转换为 DateTime