我正在尝试将对象写入文件。 由于这些对象包含字符串属性,因此在读取文件时会出现指针错误。 我该如何解决此问题,以便可以将这些复杂的对象读取/写入文件? 也许也将每个字符串的长度存储在文件中,以便以后可以阅读? 但是我不知道该怎么做? 任何帮助表示赞赏! 预先感谢。
void CPU::writeToFile() {
fstream f;
f.open("CPU.txt" , ios::out | ios::app);
if (f) {
f.write(reinterpret_cast<char*>(this), sizeof(CPU));
cout << "Write succesfull!";
}
else {
cout << "Error: while opening file";
}}
vector<CPU> CPU::download() {
fstream q;
vector<CPU> myVector;
q.open("CPU.txt", ios::binary | ios::in);
if (q) {
while (!q.eof()) {
CPU temp;
q.read(reinterpret_cast<char*>(&temp), sizeof(CPU));
myVector.push_back(temp); // store object in vector
}
}
else {
cout << "Could not open the file";
}
// delete the last read item
myVector.pop_back();
return myVector;
}
class CPU: public Component {
private:
int cores;
float speed;
public:
void writeToFile();
vector<CPU> download();
CPU();
CPU(int, float);
~CPU();
void setSpeed(int speed);
void setCores(int cores);
int getSpeed() const;
int getCores() const;
void printSpecs();
};
class Component {
protected:
int stock;
float price;
string manufacturer;
string name;
bool laptop;
public:
Component();
~Component();
void setManufacturer(string);
void setName(string);
void setPrice(float);
void setStock(int);
void setLaptop(bool);
virtual void printSpecs() = 0;
string getManufacturer() const;
string getName() const;
float getPrice() const;
int getStock() const;
bool getLaptop() const;
};