如何在二进制I / O中序列化数据?

问题描述 投票:0回答:1

这是我的C ++类和代码片段。数据未正确加载到对象中,这给了我内存访问错误。我能做什么?基类

    using namespace std;
    class Person;
    class Person
    {protected:
    int ID;
    string name;
    string address;
long int phone;
string dob;
//char pass[25];
std::string pass;

public:
Person();
Person(int ID,string name, string address, long int phone, string dob, string pass) :
    ID(ID),name(name), phone(phone),address(address),dob(dob),pass(pass)
{};

//COPY CONSTRUCTOR MUST BE CREATED INORDER TO MAKE VECTOR WORK
Person(const Person&);

virtual void showDetails() const = 0;
//MAKING THIS CLASS AN ABSTRACT CLASS

//BUNCH OF GETTERS
int getID() const;
string getName() const;
string getAddress() const;
long int getPhone() const;
string getDob() const;
string getPass() const;
void setPass(string a);
};

这里是从中派生的类:

      #include<iostream>
      #include"Person.h"
      #ifndef CUSTOMER_H
      #define CUSTOMER_H
      class Customer :public Person {
      private:
      float balance;

      protected:

      public:
      Customer() :Person(), balance(0) {}
      Customer(int ID,std::string name,std::string address,long int phone, string dob,std::string 
      pass,float balance):
      Person(ID,name,address,phone,dob,pass),balance(balance){};
      //Customer(int ID, const char* name, const char* address, long int phone, string dob, const 
      char* pass, float balance) :
      //  Person(ID, name, address, phone, dob, pass), balance(balance) {};

//COPY CONSTRUCTOR MUST BE PROVIDED, ELSE VECTOR WONT WORK
Customer(const Customer& other) :Person(other) {
    this->balance = other.balance;
}
float getBalance() const;
void showDetails() const;
// void setValues();
void deposit(float);
void withdraw(float);
};
#endif

存在无法将数据正确地从文件复制到矢量中的问题:这是文件处理的实现:

    void Controller::displayCustomers()
{

vector<Customer> custVector;
Customer cust;
fstream fin("customer.txt", ios::binary | ios::in);
while (fin.read(reinterpret_cast<char*>(&cust), sizeof(cust)));
    {
        custVector.push_back(cust);
    }
fin.close();
cout << "ID\tNAME\tADDRESS\tPHONE\t\tDOB\tPASSWORD\tBALANCE" << endl;
for (vector<Customer>::iterator itr = custVector.begin();
    itr != custVector.end(); ++itr)
{
    cout << itr->getID() << "\t" << itr->getName() << "\t" << itr->getAddress() << "\t"
        << itr->getPhone() << "\t" << itr->getDob() << "\t" << itr->getPass() <<
        "\t" << itr->getBalance() << endl;
}
cout << endl;
 }

构造器比数据成员运行更多,并且在访问向量成员时给出内存访问错误。最佳做法应该是什么?

c++ serialization file-handling
1个回答
0
投票

您不能使用二进制I / O直接读取或写入包含std::string的对象。因此此代码是错误的。

fin.read(reinterpret_cast<char*>(&cust), sizeof(cust))

最佳实践完全取决于您要实现的目标。您必须使用二进制I / O吗?你可以换班吗?您是否正在尝试对文件进行索引访问?

为了获得更好的建议,您需要陈述您实际想要实现的目标。目前,任何人都可以说此代码是错误的。

© www.soinside.com 2019 - 2024. All rights reserved.