添加到不同类中某个类类型的QList

Adding to a QList of a class type within a different class

本文关键字:类型 QList 同类 添加      更新时间:2023-10-16

我已经将类定义为事务类来指定事务详细信息:

class Transaction
{
public:
    Transaction(QString type, QDate date, int num, double price);
    QString toString();
private:
    QString m_Type;        //HOLDS THE TYPE OF TRANSACTION: Sale or Purchase
    QDate m_Date;          //date of transaction
    int m_NoOfItems;       //num of items in transaction
    double m_PricePerItem; //price per item
};

和一个存储产品信息的Product类(m_Type持有"sale"或"purchase"(:

class Product
{
public:
Product(QString name, int num, double seprice, double suprice, QString sc);
    void sell(int n);          //need to add sale to QList<Transaction>
    void restock(int n);
    QString getSupplierCode() const;
    void setProductCode(QString c);
    QString getProductCode() const;
    QList<Transaction> getTransactions() const;
    QString toString();
    void remvodeAll();
    bool isExpired();
private:
    QString m_Name;
    int m_NoOfItems;
    QString m_ProductCode;
    double m_SellingPrice;
    double m_SupplierPrice;
    QString m_SupplierCode;
    QList<Transaction> m_Transactions; //QList of class type Transaction
};

我的void Product::sell(int n)如下:

void Product::sell(int n)
{
    if(m_NoOfItems < n)
    {
        qDebug() << "Not enough items in stock.";
    }
    else
    {
        m_NoOfItems = m_NoOfItems - n;
        m_Transactions.append(Transaction("Sale", QDate.currentDate(), n, m_SellingPrice));
    }
}

这些类之间存在聚合。现在我需要做的是,每当我调用.sell()时,我都需要向类别类型为TransactionQList m_Transactions添加一个sale,其中Transaction::m_Type = "sale"。我能想到的用现有函数实现这一点的唯一方法是调用Transaction构造函数并传递值。但显然这是行不通的。你知道我该怎么解决这个问题吗?

好的,首先,您需要做的是编写:

m_Transactions.append(Transaction("Sale", QDate::currentDate(), n, m_SellingPrice));

注意QDate之后的::,因为currentDate()是一个静态函数。

我还发现将交易保存在产品内部有点奇怪。更好的设计是有一个单独的类来存储它们。