添加到不同类中某个类类型的QList
Adding to a QList of a class type within a different 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
};
和一个存储产品信息的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()
时,我都需要向类别类型为Transaction
的QList m_Transactions
添加一个sale,其中Transaction::m_Type = "sale"
。我能想到的用现有函数实现这一点的唯一方法是调用Transaction
构造函数并传递值。但显然这是行不通的。你知道我该怎么解决这个问题吗?
好的,首先,您需要做的是编写:
m_Transactions.append(Transaction("Sale", QDate::currentDate(), n, m_SellingPrice));
注意QDate
之后的::
,因为currentDate()
是一个静态函数。
我还发现将交易保存在产品内部有点奇怪。更好的设计是有一个单独的类来存储它们。
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 如何在QTScript中将QLIST内部的QMAP注册为元素类型
- 关于QLIST类型实例复制构造函数的一个奇怪问题
- Qt C++ - 创建 QList<Myclass> - 不是参数 'T 的有效模板类型参数
- Qt C++ - 不允许使用 QList<float**> 类型
- QList<float* 类型的 NULL 返回值>
- 如何在QList中对自定义类型使用qSort
- 错误:'template<class T> class QList'模板参数列表中参数 1 处的类型/值不匹配
- QList 默认参数错误消息(QList 的默认参数<QVariant>具有 int 类型)
- 将不同类型的QList转换为QString的静态函数
- 添加到不同类中某个类类型的QList