いくつかの属性(文字列)を保持する次のUser.hがあります。User.cppにはすべての定義があります。
//User.h
#ifndef USER_H
#define USER_H
#include<iostream>
#include <cstring>
using namespace std;
class User{
string username;
public:
User();
string getUsername() const;
void setUsername(string);
};
#endif
別のクラス「File」を使用して、ランダムにアクセスされた.datファイルから新しいユーザーを挿入/ユーザーを表示しています
//File.h
#ifndef FILE_H
#define FILE_H
#include "User.h"
class File{
public:
void loadUser();
bool addUser(User&);
};
#endif
ファイルクラスの定義
//File.cpp
#include<cstring>
#include<iostream>
#include<iomanip>
#include<fstream>
#include "User.h"
#include "File.h"
using namespace std;
User tempUser;
fstream usersFile;
void File::loadUser(){
usersFile.open("users.dat", ios::in | ios::binary);
usersFile.seekg(0);
// commenting the following lines prevented the issue
usersFile.read(reinterpret_cast<char *>(&tempUser), sizeof(tempUser));
cout<<tempUser.getUsername().c_str();
usersFile.close();
}
bool File::addUser(User& user){
usersFile.open("users.dat", ios::out | ios::ate | ios::binary);
// no issue when writing to file
usersFile.write( reinterpret_cast<const char *>(&user), sizeof(user));
usersFile.close();
cout<<"User added";
}
実行中に上記の問題が発生します。ただし、コンパイルの問題はありません。
内部に「文字列属性」を持つオブジェクトを処理する際に問題はありますか?
助けてください