【发布时间】:2021-09-24 10:35:49
【问题描述】:
希望大家度过了美好的一天!
我的问题是我不知道如何搜索对象的名称(如果那是正确的放置方式)。但是一个例子是:我创建了一个包含名字、姓氏、年级和出生年份的学生班级。其中一名学生的名字可能是“艾萨克”。我想要做的是在“命令提示符”中写一个名字,结果应该是我写的学生姓名的信息。如果名字没有被列为学生之一,我应该可以再试一次。
下面是我的小代码。在“search_after_student_name”中应该是计算机搜索学生的名字以查看该学生信息的地方。
#include <iostream>
#include <Windows.h>
#include <cstring>
using namespace std;
class Student {
public:
string first_name;
string last_name;
char grade;
int birth;
Student(string aFirst_name, string aLast_name, char aGrade, int aBirth) {
first_name = aFirst_name;
last_name = aLast_name;
grade = aGrade;
birth = aBirth;
}
};
void search_after_student_name(string hisFirst_name)
{
if (hisFirst_name != student.first_name) //Is not like that, but just an example of how I am going to use it
cout << "We couldn't find the name you wrote. Try again" << endl;
else() //if the "hisFirst_name" matches a student:
{
cout << "info about this student...";
}
}
int main()
{
SetConsoleCP(1252);
SetConsoleOutputCP(1252);
Student student1("Oliver", "Twist", 'C', 1999);
Student student2("James", "Free", 'D', 2000);
Student student3("Isaac", "Lee", 'A', 2000);
string namn;
cout << "Write in the name that you want to search: ";
cin >> namn;
search_after_student_name(namn);
return 0;
}
我希望你能理解我的愚蠢代码问题并帮助我。谢谢!
【问题讨论】:
-
这段代码的编写方式你无法搜索任何内容。您的对象的范围是
main,您的函数无法访问这些对象。如果您打算进行搜索,您应该将它们真正存储在某种数据结构中(例如:std::vector或std::map) -
您需要创建一个学生数组或向量,并将其与要搜索的名称一起传递给您的搜索函数。然后就可以使用this来查找对象了。
-
我建议 OP 清除他/她的 OOP 概念。谁让数据成员公开?
-
@ILoveLogCat 这只是我想做的一个小任务,仅此而已。