如何将一个类的对象传递给同一类的函数
How to pass an object of a class to a function of the same class?
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);
}
}
我有两个函数在我的学生类:studentRegister()
和studentLogin()
。当调用studentRegister时,它接受学生的所有详细信息,然后将相应类的对象写入一个DAT文件。现在,当登录时,我正试图使用in.read((char *)&s, sizeof(Student));
但是,这会导致运行时错误并突然关闭控制台。出了什么问题?
读和写不像你想的那样工作。它们只适用于没有指针的类,但是字符串有指针,而你的类有字符串,所以你不能使用它们。
你必须找到一种不同的方式来读写你的数据。这是怎么了
out << studentName << ' ' << roll << ' ' << studentPassword << 'n';
和
in >> studentName >> roll >> studentPassword;`
也不是你问的问题,但in
和out
不应该在你的Student
类声明。它们应该在使用它们的函数中声明。
相关文章:
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 如何使用connect将qml按钮与同一类的cpp函数连接起来
- 类成员函数无法访问同一类的私有结构节点?
- 无法将指向类的成员函数的函数指针作为参数传递给同一类的另一个成员函数
- 在 c++ 中将对象设置为等于同一类的构造函数是否有效?
- 如何将一个类的成员函数用作另一类的友元函数
- 如何获取同一类函数中类成员的函数指针?
- 一类嵌套类不能用作模板函数类型名
- 在多个文件中与同一类分开函数
- 将1D或2D向量传递给同一类的构造函数
- 仅一个功能的链接错误.在同一类和CPP文件中具有相似签名的其他函数工作正常
- 让构造函数在其初始化列表中调用同一类的另一个构造函数是否有效
- 如何将两个类成员函数与同一类中的另一个函数一起添加
- 在C++中,类是否可以包含指向构造函数中初始化的同一类的指针?
- C 使用来自另一类的函数
- 如何为同一类对象的成员函数保留单独的变量副本?
- 如何将成员函数用于同一类的不同对象
- 为什么一个非平凡的成员需要为同一类中的匿名联合定义构造函数
- 如何将Qt类中声明的结构传递给同一类的函数?