C++ C++;创建没有默认构造函数的对象数组
动态创建(事务)对象的数组时出错。错误输出显示:“调用'Transaction::Transaction()'时没有匹配的函数” 这是赋值的一部分,我们不允许使用默认构造函数。根据我收集的信息,数组在创建时会自动将值分配给其每个索引地址,并且由于没有为事务创建默认构造函数,因此如果没有值,它无法执行此操作。请帮助我了解如何修复此错误C++ C++;创建没有默认构造函数的对象数组,c++,arrays,pointers,object,constructor,C++,Arrays,Pointers,Object,Constructor,动态创建(事务)对象的数组时出错。错误输出显示:“调用'Transaction::Transaction()'时没有匹配的函数” 这是赋值的一部分,我们不允许使用默认构造函数。根据我收集的信息,数组在创建时会自动将值分配给其每个索引地址,并且由于没有为事务创建默认构造函数,因此如果没有值,它无法执行此操作。请帮助我了解如何修复此错误 class Transaction { private: int id; float amount; string fromAddress, toAdd
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
是处理此问题最简单(也是最好)的方法:
class Block {
public:
Block()
: txList(MAX_TX, Transaction("a", "b", "C", 0.0f)) {}
private:
std::vector<Transaction> txList;
};
类块{
公众:
块()
:txList(MAX_TX,事务(“a”、“b”、“C”、0.0f)){}
私人:
std::向量txList;
};
如果这是您的“任务”,并且不允许您使用默认构造函数,我假设您需要使用以下其中一种:
malloc
在引擎盖下使用std::vector
malloc
Transaction* transactionsList = (Transaction*) malloc(size * sizeof(Transaction));
编辑:不要忘记,在malloc
之后,您可以使用free
和not删除
来释放内存
<>我必须注意,在C++中,使用<代码> MalOC 通常会有利于<代码>新< /代码>。std::vector<Transaction> transactionsList(size, *default_value*);
然后使用
emplace\u back()
或push\u back()
添加新元素如果坚持使用普通动态数组,可以执行以下操作:
但您可以将构造函数声明为:
Transaction(string in_fA = "a", string in_tA = "b", string in_sign = "c", float in_amount = 42);
使用
std::vector
和push_-back
/emplace_-back
。如果您仍想使用指针,并想将所有对象初始化为相同的值,那么您可以这样做,例如*txList=new Transaction[MAX_TX](参数传递给所有构造函数)
Define default constructor?顺便说一句,目前,txList
尚未初始化,您可能需要类似于txList=new Transaction*[MAX_TX];for(int i=0;i!=MAX_TX;+++i){txList[i]=new Transaction(/*parameters*/)}
*txList = new Transaction[MAX_TX]{{"1", "2", "3", 4},
// 3 more
{"5", "6", "7", 8}};
Transaction(string in_fA = "a", string in_tA = "b", string in_sign = "c", float in_amount = 42);