【发布时间】:2018-01-22 15:34:34
【问题描述】:
动态创建(事务)对象数组时出现错误。错误输出说:“没有匹配函数调用'Transaction::Transaction()' 这是赋值的一部分,我们不允许使用默认构造函数。从我收集的内容来看,一个数组在创建时会自动为其每个索引地址分配值,并且由于没有为事务创建默认构造函数,因此没有值就无法执行此操作。请帮我看看我能做些什么来解决这个错误。
class Transaction
{
private:
int id;
float amount;
string fromAddress, toAddress, signature;
bool confirmed, removeFromPool;
static int numTransactions;
public:
Transaction(string in_fA, string in_tA,string in_sign,float in_amount);
Transaction(Transaction &obj);
int getId() const;
}
//---------------------
class Block
{
private:
int id, txCount;
const int MAX_TX=5;
Transaction** txList;
string blockHash, prevBlockHash, minerName;
bool confirmed;
public:
Block(int id,string prevH,string name);
}
//------------------
// block.cpp
Block::Block(int i, string prevH, string name)
{
*txList = new Transaction[MAX_TX];
}
【问题讨论】:
-
使用
std::vector和push_back/emplace_back。 -
如果您仍想使用指针并将所有对象初始化为相同的值,那么您可以执行例如
*txList = new Transaction[MAX_TX](parameters_passed_to_all_constructors) -
定义默认构造函数?
-
顺便说一句,目前,
txList尚未初始化,您可能想要txList = new Transaction*[MAX_TX]; for (int i = 0; i != MAX_TX; ++i) { txList[i] = new Transaction(/*parameters*/); }之类的东西
标签: c++ arrays pointers object constructor