通过多个类访问成员时出错
Error when accessing member over multiple classes
我是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
。我怀疑这可能是问题所在,但我不确定在通过Blockchain
和Block
类调用时间戳时,我还能如何访问时间戳。
当前,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());
}
相关文章:
- 在成员dynamic_bitset上使用 boost::from_block_range 时出错,但在本地dynamic
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 在 Clang 中使用指向成员的指针时出错
- LNK2019 在文件中调用静态成员的方法时出错.cpp
- 当两个成员位于同一类中时出错"a nonstatic member reference must be relative to a specific object"
- 通过多个类访问成员时出错
- 将私有数据成员作为默认参数传递给该类的公共方法时出错
- 类和成员函数模板专用化出错
- 在VS2015中访问类成员时运行时错误,但在Linux上未访问时出错
- 缺少类型说明符 - int 假定 声明静态成员后出错
- 编译特征程序时出错:错误:'seq'不是'Eigen'的成员
- 调用指向成员函数的指针时出错
- 修改另一个类的向量成员时出错
- 向模板化静态成员初始化添加和不添加'typename'都会出错
- 非标准语法;使用 '&' 创建指向成员的指针错误,将成员函数分配给向量时出错
- 推导成员函数包装器的返回类型时出错
- 编译类模板成员函数时出错
- 在 C++ 中访问泛型结构的成员会出错
- 初始化作为结构成员的函数指针时出错
- 类中的const成员出错