在 C++ 中将 class 向量导出到 .dat

Exporting class vector to .dat in C++

所以我正在用 C++ 制作一个基本的加密货币,我正在尝试将区块链导出到 .dat 文件,以便对等方可以下载区块链

区块链class:

#ifndef BLOCKCHAIN_H
#define BLOCKCHAIN_
#include <cstdint>
#include <vector>
#include "block.hpp"
class Blockchain
{
    public:
        Blockchain();
        void add_block(Block new_block);
        std::vector<Block> chain;
    private:
        int difficulty;
        Block get_last_block();
};
#endif

在本例中,我要导出的区块链是 chain,所以我希望能够使用 ofstream 将其写入 dat

我试着写这个,但它给出了一个分段错误:


#include "blockchain/blockchain.hpp"
#include <fstream>
#include <iterator>
std::ostream & operator<<(std::ostream & out, const Block & p) {
    out << p << std::endl;
    return out;
}
std::ostream & operator<<(std::ostream & out, const Blockchain & p) {
    out << p << std::endl;
    return out;
}
int main()
{
    
    Blockchain block_chain = Blockchain();
    std::ofstream outFile("test.dat");

    int i = 0;
    for(; 1 == 1 ;){
        std::cout<<block_chain.chain.size();
        i++;
        std::cout << "Mining block "<<i<<std::endl;
        block_chain.add_block(Block(i, "Block 1 Data"));
        for (const auto &e : block_chain.chain) outFile << e << "\n";
    }


    return 0;
}

问题就在这里

std::ostream & operator<<(std::ostream & out, const Blockchain & p) {
    out << p << std::endl;
    return out;
}

我不确定您的期望是什么,但您已经编写了一个只调用自身的函数。因此,当您尝试输出区块链时,您只会遇到堆栈溢出,这就是您的程序崩溃的原因。

您需要做的是编写 std::ostream & operator<<(std::ostream & out, const Blockchain & p) 以便它调用一系列输出操作来输出块链的各个部分(无论它们是什么)。

您的 Block 接线员有同样的问题。