C++ 如何将类的对象传递给同一类的函数? intmain(){ 智力选择; 流进流出; 开关(选择) { 案例1: filename=s.studentRegister(); open(filename.c_str(),ios::out); 写出((字符*)&s,大小(学生)); cout
读和写不能像你所尝试的那样工作。它们只适用于没有指针的类,但是string有指针,而你的类有string,所以你不能使用它们 你必须找到一种不同的方式来读写你的数据。这有什么问题吗C++ 如何将类的对象传递给同一类的函数? intmain(){ 智力选择; 流进流出; 开关(选择) { 案例1: filename=s.studentRegister(); open(filename.c_str(),ios::out); 写出((字符*)&s,大小(学生)); cout,c++,C++,读和写不能像你所尝试的那样工作。它们只适用于没有指针的类,但是string有指针,而你的类有string,所以你不能使用它们 你必须找到一种不同的方式来读写你的数据。这有什么问题吗 int main(){ int choice; fstream in, out; switch(choice) { case 1: filename = s.studentRegister(); out.
int main(){
int choice;
fstream in, out;
switch(choice)
{
case 1:
filename = s.studentRegister();
out.open(filename.c_str(), ios::out);
out.write((char *)&s, sizeof(Student));
cout<<endl<<"Registered successfully."<<endl;
case 2:
s.studentLogin();
}
}
class Student
{
std::string studentName, roll, studentPassword;
fstream in, out;
public:
std::string studentRegister()
{
cout<<"Enter roll number"<<endl;
cin>>roll;
cout<<"Enter current semester"<<endl;
cin>>ch;
cout<<"Enter your name"<<endl;
cin>>studentName;
cout<<"Enter password"<<endl;
cin>>studentPassword;
return (roll+".dat");
}
void studentLogin()
{
Student s;
cout<<"Enter roll number: "<<endl;
cin>>roll;
cout<<"Enter password: "<<endl;
cin>>studentPassword;
filename = roll + ".dat";
in.open(filename.c_str(), ios::in);
in.read((char *)&s, sizeof(Student));
read.close();
if((studentPassword.compare(s.studentPassword)==0))
{
system("cls");
cout<<"Welcome "<<s.studentName<<"!"<<endl;
displayStudentMenu();
}
else
{
cout<<"Invalid user";
exit(0);
}
}
也不是你问的问题,而是
in
和out
不应该在你的Student
类中声明。它们应该在你使用它们的函数中声明。正如你在另一个问题中提到的,你根本不能用这些方法编写和阅读你的类。(此外,问题标题与实际问题无关。)请提供一个简短完整的示例程序。有关更多详细信息,请参阅。非常感谢!我在文件中存储了几个字符串,不知道如何随机访问它们(不使用seekg()).in工作正常。顺便说一句,in也能正确读取DAT和二进制文件,还是仅仅读取文本文件?读取会从任何类型的文件中读取字节,写入会将字节写入任何类型的文件。问题是你有其他东西。也就是说,你不能将像字符串(或你的学生)这样的对象视为字节的平面序列。它们具有内部结构(使用指针等)读写都不知道。
out << studentName << ' ' << roll << ' ' << studentPassword << '\n';
in >> studentName >> roll >> studentPassword;`