通过多个类访问成员时出错

Error when accessing member over multiple classes

本文关键字:成员 出错 访问      更新时间:2023-10-16

我是C++的新手,我正在编写一个简单的区块链程序作为一种练习。当我运行下面的代码时,我似乎得到了一个错误:

Process returned -1073741819 (0xC0000005)

代码如下:

#include <iostream>
#include <time.h>
#include <string>
using namespace std;
class Block
{
int data, previous_hash;
public:
string timestamp;
Block(string a, int b, int c)
{
timestamp = a;
data = b;
previous_hash = c;
};
};
string getTime()
{
time_t now = time(NULL);
struct tm tstruct;
char buf[40];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%X", &tstruct);
return buf;  //Simple code to return current time
}
class BlockChain
{
public:
Block chain[];
BlockChain()
{
chain[0]=createGenesisBlock();
}
Block createGenesisBlock()
{
return Block(getTime(), 10, 0);
}
};
int main()
{
BlockChain myChain;
cout << "current time is " << getTime();
cout << myChain.chain[0].timestamp; //Is this correct?
}

我在main((中包含了一行,用于访问对象mychain中的字符串timestamp。我怀疑这可能是问题所在,但我不确定在通过BlockchainBlock类调用时间戳时,我还能如何访问时间戳。

当前,BlockChain::chain是一个大小未知的数组。但是,当您在BlockChain的构造函数中访问chain[0]时,您假设chain指向有效内存,但事实并非如此,因为您从未初始化过它。这就是为什么您会因内存访问错误而崩溃。我建议使用std::vector<Block>而不是Block[],您可以根据需要调整其大小:

class BlockChain {
public:
std::vector<Block> chain;
BlockChain() {
// initialize and append a new block to chain
chain.emplace_back(createGenesisBlock());
}