如题,为什么在ofs.write和ifs.read的时候需要添加引用?
如果没有引用的话编译器报错:
Error (active) no suitable conversion function from "Maker" to "const char *" exist
按照编译器报的错,加了引用就有转换的函数了?
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
using namespace std;
class Maker {
public:
Maker() = default;
Maker(const char * name,int age) {
strcpy(this->name, name);
this->age = age;
}
void printM() {
cout<<this->age<<" " << this->name<< endl;
}
public:
char name[64];
int age;
};
int main()
{
Maker m1("小林", 20);
Maker m2("布林", 22);
ofstream ofs;
ofs.open("test.dat", ios::out |ios::binary );
if (!ofs.is_open()) {
cout << "打开文件失败" << endl;
}
ofs.write((const char *)&m1, sizeof(Maker));//这里强制类型转换,会产生临时量
ofs.write((const char *)&m2, sizeof(Maker));
ofs.close();
ifstream ifs;
ifs.open("test.dat", ios::in | ios::binary);
if (!ifs.is_open()) {
cout << "dakaiwenjianshibai" << endl;
}
Maker m3;
Maker m4;
ifs.read((char*)&m3, sizeof(Maker));
ifs.read((char*)&m4, sizeof(Maker));
m3.printM();
m4.printM();
system("pause");
return 0;
}