【发布时间】:2021-09-27 05:41:00
【问题描述】:
以下代码使用成员函数save()将数据保存在文件中,并使用静态函数load()读回数据。
使用load()函数加载数据成功,但使用dump()函数打印结果出乎意料,提供图片链接供参考(@ 987654321@).
从 main() 访问类的成员会得到正确的结果。
谁能找出我的代码有什么问题。
#include <bits/stdc++.h>
using namespace std;
class Person {
public:
int ID;
char name[20];
Person() { ID = -1; memset(name, '\0', 20); }
void get_data();
void dump();
bool save();
static Person *load(int id);
};
void Person::get_data() {
cout << "Enter ID: ";
cin >> ID;
cout << "Enter name: ";
cin.ignore();
cin.get(name, 20);
}
void Person::dump() {
cout << "ID : " << this->ID << endl;
cout << "Name: " << this->name << endl;
}
bool Person::save() {
ofstream outfile("person.dat", ios::app | ios::binary);
if(!outfile) { return false; }
outfile.write((char*)this, sizeof(Person));
outfile.close();
return true;
}
Person *Person::load(int id) {
Person tmp, *p;
ifstream infile("person.dat", ios::binary);
if(!infile) { return NULL; }
while(true) {
infile.read((char*)&tmp, sizeof(Person));
if( infile.eof() ) break;
if(tmp.ID == id) {
infile.close();
p = &tmp;
return p;
}
}
infile.close();
return NULL;
}
int main(int argc, char *argv[]) {
if(argc == 1) { // if statement to save data to file
Person p;
p.get_data(); // get user input[enter image description here][1]
if( p.save() ) cout << "Save successfull\n"; // save data
else cout << "Save aborted\n";
}
else { // if statement to load data from file
Person *p;
int id;
cout << "Enter person ID to search: ";
cin >> id;
p = Person::load(id); // load data
if( !p ) {
cout << "Person not found\n";
} else {
printf("%d, %s\n", p->ID, p->name); // gives right result
p->dump(); // gives wrong result
}
}
return 0;
}
[1]:
【问题讨论】:
-
你应该给minimal reproducible example。此外,使用
#include <bits/stdc++.h>被视为bad practice。 -
p = &tmp;:tmp一旦load()返回就停止存在,所以p指向你的主内存无效。从那时起,您就处于未定义行为领域,这意味着不可预测的结果。 -
找不到骗子,但您正在返回指向临时对象的指针。加速你的编译器警告。
标签: c++ file class object pointers