类中的数组

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