c++ - 如何将一个类的对象传递给同一个类的函数?

标签 c++

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);
    }

}

我的 Student 类中有两个函数:studentRegister()studentLogin()。当调用 studentRegister 时,它接受学生的所有详细信息,然后将相应类(class)的对象写入 DAT 文件。现在,登录时,我尝试使用 in.read((char *)&s, sizeof(Student));

但是,这会导致运行时错误并且控制台会突然关闭。出了什么问题?

最佳答案

读写不能按照您尝试的方式工作。它们只适用于没有指针的类,但是字符串有指针,而你的类有字符串,所以你不能使用它们。

您将不得不找到一种不同的方式来读取和写入您的数据。这是怎么回事

out << studentName << ' ' << roll << ' ' << studentPassword << '\n';

in >> studentName >> roll >> studentPassword;`

也不是你问的问题,但 inout 不应该在你的 Student 类中声明。它们应该在您使用它们的函数中声明。

关于c++ - 如何将一个类的对象传递给同一个类的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15500141/

相关文章:

C++ Matrix-Chain-Order/无法获得所需的输出

c++ - 使用打印不同范围的 3 个线程按排序顺序打印数字

c++ - 如何阻止 Py_Initialise 使应用程序崩溃?

c++ - 是什么导致了错误 "Stack around the variable ' ' was corrupted"in my program

c++ - 一个 System v 消息队列用于多进程读/写的问题

c++ - 提取十六进制数的 'parts'

c++ - 将 5 个 vector 合并到矩阵 C++

c++ - 当我取消注释移动构造函数 A(A&&) 时,下面的代码片段会发生什么?

c++ - 避免在 vim 中从 DoxygenToolkit 打印参数

c++ - 默认预处理器定义和跨平台编译