1

我是 C++ 新手,刚刚在我看过的课程中学习了类,我正在尝试制作一个小区块链项目,但在构造函数方面遇到了麻烦。我有一个类,Transaction它的构造函数接受三个参数,并试图使它成为另一个类Block的构造函数的参数。这是构造函数的定义Transaction

Transaction::Transaction(std::string fromAddress, std::string toAddress, uint32_t amount)
{
    this->fromAddress = fromAddress;
    this->toAddress = toAddress;
    this->amount = amount;
}

我正在尝试使用Transaction该类作为该类的Block参数

Block::Block(time_t timestamp, Transaction transaction(std::string fromAddress, std::string 
toAddress, uint32_t amount), std::string prevHash)
{
    this->timestamp = time(nullptr);
    this->transactionSet(std::string fromAddress, std::string toAddress, uint32_t amount) = 
transaction(std::string fromAddress, std::string toAddress, uint32_t amount);
    this->prevHash = "";
}

但是这样做会遇到很多错误,我尝试了很多不同的方法,但我不知道如何实现它,那么如何使用参数化对象作为另一个类的参数呢?

4

1 回答 1

2

对象构造发生在您将其作为参数传递给函数或方法之前。并在施工时设置参数。当一个方法接受一个对象作为参数时,该对象是否具有参数化构造函数对方法无关紧要。根据您定义构造函数的方式,您必须首先Transaction在调用站点创建一个对象,然后将其传递给方法。

Block::Block(time_t timestamp, Transaction transaction, std::string prevHash)
{
    this->timestamp = time(nullptr);
    this->transactionSet = transaction;
    this->prevHash = prevHash;
}

将创建一个对象,Block如下所示:

time_t tm;
time(&tm);
Block block(tm, Transaction("X", "Y", 100), "YourHash");

或者

...
Transaction t("X", "Y", 100);
Block block(tm, t, "YourHash");

可以注意到,构造函数与 的参数化构造函数无关Transaction


但是,还有另一种方法可以将 new 的创建委托TransactionBlock的构造函数:

Block::Block(time_t timestamp, std::string fromAddress, std::string toAddress, uint32_t amount, std::string prevHash)
{
    this->timestamp = timestamp;
    this->transactionSet = Transaction(fromAddress, toAddress, amount);
    this->prevHash = prevHash;
}

在这里,你不是传入一个新的事务,而是告诉Block构造函数:这里是构造函数的参数Transaction,使用它们来创建一个新的Transaction

Block block(tm, "X", "Y", 100, "YourHash");

成员初始化器列表

另外,有一些程序员兄弟提到过,您的构造函数可以使用成员初始化器列表更简洁地编写:

Block::Block(time_t ts, Transaction t, std::string previousHash) 
: timestamp(ts), transactionSet(t), prevHash(previousHash)
{
}

初始化器列表旨在将成员初始化从构造函数中取出,以便构造函数的主体保持清洁。如您所见,构造函数主体现在是空的。初始化列表的语法是:

ClassName(
    type_1 parameter_name_1, 
    type_2 parameter_name_2, 
    ... type_n parameter_name_n) 
    : member_name_1(parameter_name_1),
      member_name_2(parameter_name_2),
  ... member_name_n(parameter_name_n)
{
    // constructor body
}
于 2021-06-18T07:38:02.847 回答