类中的数组
Array in Classes
本文关键字:数组 更新时间:2023-10-16
我对类还是个新手,所以这里是我迄今为止所做的工作。在这个程序中,我必须提示用户输入多少产品和价格,我必须再次显示如下:
No Product Code Price
1 101 4.50
并计算平均价格。
我的类必须容纳多达100个对象,我仍然不确定如何实现这些对象。希望有人能帮我。
#include <iostream>
using namespace std;
class Product{
private :
int code;
double price;
public :
Product ();
void setCode(int);
void setPrice(double);
int getCode();
double getPrice();
};
Product :: Product()
{
code = 0;
price = 0;
}
void Product :: setCode(int c)
{
code = c;
}
void Product :: setPrice(double p)
{
price = p;
}
int Product :: getCode()
{
return code;
}
double Product :: getPrice()
{
return price;
}
int main(){
const int size = 100;
Product m[size];
int procode;
double proprice;
int num;
double sum= 0;
cout << "How many products to enter? ";
cin >> num;
cout << endl;
for(int i=0; i<num ;i++)
{
cout << "Enter the information of product #"<< (i+1)<<endl;
int code;
cout << "tProduct Code: ";
cin >> code;
m[i].setCode( code );
double price;
cout << "tPrice: ";
cin >> price;
m[i].setPrice( price );
sum = sum + price;
}
///output??
cout <<"No"<<" "<<"Product Code"<<" "<<"Price" <<endl;
cout<<" "<<m[i].getCode()<<" "<<m[i].getPrice()<<endl;
cout<<"Average: " << sum/num << endl;
return 0;
}
for(int i=0; i<num ;i++)
{
cout << "Enter the information of product #"<< (i+1)<<endl;
cout << "Product Code:";
cin >> procode;
m[i].setCode(procode);
cout < "nPrice:";
cin >> proprice;
m[i].setPrice(proprice);
}
这将设置所需的对象数量。
作为访问
cout<<m[index].getCode()<<m[index].getPrice();
您的意思是动态分配吗?如果您想让用户指定数量可变的产品,您必须在知道num
之后动态创建阵列。例如:
int main() {
Product * m;
int num;
cout << "How many products to enter? ";
cin >> num;
cout << endl;
m = new Product[num];
for (int i=0; i<num; i++) {
// something with the array
}
delete [] m;
return 0;
}
函数main可以用以下方式编写
int main()
{
const size_t MAX_ITEMS = 100;
Product m[MAX_ITEMS];
size_t num;
cout << "How many products to enter? ";
cin >> num;
if ( MAX_ITEMS < num ) num = MAX_ITEMS;
for ( size_t i = 0; i < num; i++ )
{
cout << "nEnter the information of product #" << (i+1) << endl;
int code;
cout << "tProduct Code: ";
cin >> code;
m[i].setCode( code );
double price;
cout < "tPrice: ";
cin >> price;
m[i].setPrice( price );
}
// here can be the code for output data
return 0;
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '