如何读写我的班级向量?

时间:2019-12-28 13:35:15

标签: c++ file vector fwrite fread

我创建了一个指针向量,其中有三角形和矩形的外接参考。 从理论上讲,编写和读取都可以,但是当我想读取二进制文件时,会出现一堆奇怪的符号,我不知道该如何解决。 当我想从文件中读取时,附上了输出图片:

enter image description here

我在代码中写了我认为可能是个问题的代码,但是我不知道如何解决这个问题。谢谢您的帮助!

这是我的代码的一部分:

class Polygon {
public:
    virtual void circumreference()=0;
    virtual void print() = 0;
};

class Triangle: public Polygon{ //there are some functions}
class Rectangle: public Polygon{ //there are some functions}

int main() {
    vector<Polygon*> figures;

    Triangle trian(1, 2, 3);
    trian.circumreference();
    trian.print();
    Rectangle rect(1, 2, 3, 4);
    rect.circumreference();
    rect.print();

    Polygon* pol = new Triangle(2,3,4);
    figures.push_back(pol);

    Polygon* pol1 = new Rectangle(4,5,6,7);
    figures.push_back(pol1);


    for (int i = 0; i < figures.size(); ++i){
        figures[i]->circumreference();
        figures[i]->print();
    }

    ofstream outfile;
    outfile.open("figures.bin", ios::out | ios::trunc | ios::binary);
    for (auto val : figures) {

//I think that sizeof(Polygon) might be a problem - I don't know how to do that

        outfile.write(reinterpret_cast<const char*>(&val), sizeof(Polygon));
        if (outfile.bad()) {
            throw runtime_error("Saving to  file failed.\n");
        }
    }
    cout << "Writing to file ended succesfully." << endl;

    ifstream infile;
    infile.open("figures.bin", ios::in | ios::binary);
    while (infile) {
        Polygon* val;
        infile.read(reinterpret_cast<char*>(&val), sizeof(Polygon));
        if (infile.bad()) {
            throw runtime_error("Reading failed.\n");
        }
        if (infile.eof())break;
        figures.push_back(val);
    }
    cout << "Reading from file:";
    for (auto val : figures) {
        cout << val<<",";
    }
    cout << "\nReading from file is done";

    return 0;
}

我知道我的代码看起来很复杂且混乱,但是首先我想学习如何做以及如何对其进行优化。

0 个答案:

没有答案