在程序中传递功能具有结构C

passing a function in a program has a struct c++

本文关键字:结构 功能 程序      更新时间:2023-10-16

我在解决此问题方面正在努力解决此问题,但我不知道确切的错误在哪里。

这个问题是关于结构的练习,它需要用户输入2个学生的名字及其年龄,并使用struct返回老年人的名称,以及用于返回学生名称的功能。

#include <iostream>
#include <string>
using namespace std;
struct student{
    string name;
    int age;
};
student getOlder(student s1, student s2);
int main()
{
    student s1, s2, Max;
    cout << "Enter the first sudent's name" << endl;
    getline(cin, s1.name);
    cout << "Enter the first sudent's age" << endl;
    cin >> s1.age;
    cout << "Enter the second sudent's name" << endl;
    getline(cin, s2.name);
    cout << "Enter the second sudent's age" << endl;
    cin >> s2.age;
    Max = getOlder(s1, s2);
    cout << Max << " is the older student " << endl;
}
student getOlder(student s1, student s2)
{
    if (s1.age > s2.age){
        cout << s1.name << endl;
    }
    cout << s2.name << endl;
    return result;
}

您需要退还年长的学生:

student getOlder(student s1, student s2)
{
  if (s1.age > s2.age)
  {
     return s1;
  }
  return s2;
}

另外,由于您没有更改s1s2的内容,因此应将它们作为常量参考传递:

student getOlder(const student& s1, const student& s2)
{
 // ...
}

编辑1:超载比较操作员
可选,您可以添加方法以进行比较:

struct student
{
  std::string name;
  unsigned int age; // int implies age can be negative.
  bool operator>(const student& s2)
  {
     return age > s2.age;
  }
}

这使您可以写出以下内容:

if (s1 > s2)
{
  cout << "Student " << s1.name << " is older than " << s2.name << endl;
}

问题是您的最终功能中的result从未声明。您可以在IF/else期间设置等于s1s2

student result;
if(s1.age>s2.age){
    result=s1;
}else{
    result=s2;
}
return result

,或者您可以跳过result部分,然后退还学生:

if (s1.age > s2.age)
{
    return (s1);
}
    return(s2);