【问题标题】:C++ Create Object Array without default constructorC++ 创建没有默认构造函数的对象数组
【发布时间】: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::vectorpush_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


【解决方案1】:

如果你坚持使用一个普通的动态数组,你可以这样做:

*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);

因此试图避开愚蠢的“无默认 ctor”要求。

【讨论】:

    【解决方案2】:

    使用std::vector 是处理这个问题的最简单(也是最好)的方法:

    class Block {
    public:
      Block()
        : txList(MAX_TX, Transaction("a", "b", "C", 0.0f)) {}
    
    private:
      std::vector<Transaction> txList;
    };
    

    【讨论】:

      【解决方案3】:

      如果这是您的“分配”并且您不允许使用默认构造函数,我假设您应该使用其中之一:

      • malloc
      • std::vector 在后台使用 malloc

      第一个选项中内存分配是这样的:

      Transaction* transactionsList = (Transaction*) malloc(size * sizeof(Transaction));
      

      编辑:不要忘记在malloc 之后使用free delete 来释放内存。

      我必须注意,malloc 在 C++ 中的使用通常不鼓励使用 newnew 的重点是将两个阶段合并在一起:内存分配和内存初始化(+指针类型对话为您完成)。但是,你需要的只是分配一块内存,你可以考虑 malloc。无论如何,take a look at this

      Jarod42Frank 指出的第二个选项:

      std::vector<Transaction> transactionsList(size, *default_value*);
      

      你得到size元素的向量,每个元素都被初始化为你指定的默认值。

      如果允许定义移动Transaction(Transaction&amp;&amp; obj) = default;或复制构造函数Transaction(const Transaction&amp; obj) { ... },也可以保留内存:

      std::vector<Transaction> transactionsList;
      transactionsList.reserve(size);
      

      然后使用emplace_back()push_back() 添加一个新元素。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-04
        • 2017-08-21
        • 1970-01-01
        • 2021-03-02
        • 2011-06-12
        • 1970-01-01
        • 2019-11-22
        相关资源
        最近更新 更多