添加到不同 class 中的 class 类型的 QList

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

我已经定义了class一个交易class来指定交易细节:

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

和用于存储产品信息的产品 class(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));
    }
}

这些 class 之间存在聚合。现在我需要做的是,每当我调用 .sell() 时,我都需要向 QList m_Transactions 添加销售,它是 class 类型 Transaction,其中 Transaction::m_Type = "sale"。我能想到的对现有函数执行此操作的唯一方法是调用 Transaction 构造函数并传入值。但显然那是行不通的。我有什么办法可以解决这个问题吗?

好的,首先,你需要做的是写:

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

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

我也觉得在产品中保存交易有点奇怪。更好的设计是有一个单独的 class 来存储它们。