没有默认构造函数的C ++创建对象数组 [英] C++ Create Object Array without default constructor

查看:201
本文介绍了没有默认构造函数的C ++创建对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

动态创建(事务)对象数组时出现错误.错误输出显示:没有匹配函数可调用'Transaction :: Transaction()' 这是分配的一部分,我们不允许使用默认构造函数.从我收集的数据来看,数组在创建时会自动为其每个索引地址分配值,并且由于没有为Transaction创建默认构造函数,因此如果没有值,它将无法执行此操作.请帮助我看看如何解决此错误.

I get an error when dynamically creating an array of a (transaction) object. The error output says:"no matching function for call to 'Transaction::Transaction()' This is part of an assignment and we are not allowed to use a default constructor. From what I gather an array automatically assigns values to each of its indexed address when it's created and as no default constructor is made for Transaction, it cannot do this without values. Please help me see what I could do to fix this error.

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

推荐答案

如果您坚持使用普通的动态数组,则可以做到这一点:

If you insist on using a plain dynamic array, you could do this:

*txList = new Transaction[MAX_TX]{{"1", "2", "3", 4},
                                  // 3 more
                                  {"5", "6", "7", 8}};


但是相反,您可以将构造函数声明为:


But instead you could declare your constructor as:

Transaction(string in_fA = "a", string in_tA = "b", string in_sign = "c", float in_amount = 42);

因此尝试避开愚蠢的没有默认ctor"要求.

And thus attempt to dodge the silly 'no default ctor' requirement.

这篇关于没有默认构造函数的C ++创建对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆