传递对象数组以进行搜索

Passing an array of objects for search

本文关键字:搜索 数组 对象      更新时间:2023-10-16
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class student
{ int rno;
  char name[20];
  float total;
  public:
  void In();
  void Out();
  void search(student ob[50],int,int);
  int retrno()
  { return rno;               //returns the roll no of student 
  }
};
void student::search(student ob[],int n,int srno)
{ int flag=0;
  for(int i=0;i<n;++i)
     if(ob[i].retrno()==srno)     //checking for rollno match
       { flag=1;
         cout<<"Student found";
         ob[i].Out();                 //calling Out() when match is found
       }
   if(flag==0)
   cout<<"No matching records";
}
void student::In()
{ cout<<"Enter rno:";
  cin>>rno;
  cout<<"Enter name:";
  gets(name);
  cout<<"Enter total:";
  cin>>total;
}
void student::Out()
{ cout<<"rno:";
  cout<<rno;
  cout<<"Name:";
  puts(name);
  cout<<"Total:";
  cout<<total;
}
void main()
{ student ob[50];
  int n,srno;
  cout<<"Enter no. of students:";
  cin>>n;
  for(int i=0;i<n;++i)
       ob[i].In();                    //In() is called n times
  cout<<"Enter rno to be searched:";
  cin>>srno;
  ob.search(ob,n,srno);
 }

编译时出现 2 个错误。

11: Undefined structure 'student'
52: Structure required on left side of . or .*

我试图查看函数原型中是否有错误,但它看起来不错。我厌倦了没有数组大小的原型并获得了相同的错误。我也尝试全局初始化类,但遇到了同样的错误(我没有想法(。请帮我找到问题所在。

您的student类代表一个学生,我认为搜索功能最好不要成为它的成员,考虑到您也向它传递了一个学生数组:

void search(student ob[], int n, int srno)
{
    // ... keep your implementation
}

然后你可以用以下命令调用它:

search(ob,n,srno);

最好将输出部分分开,并使搜索函数仅返回指向找到(或未找到(元素的索引或指针。

我同意 Ulrich Eckhardt 关于所包含库的观点。

我想补充一点,您应该以某种方式检查用户输入的内容,我想记住这更正确使用:

int main() {
    // ... stuff...
    return 0;
}