2017-03-01 65 views
-4

我很努力地解决这个问题,不管它的简单性,但我不知道确切的错误在哪里。在程序中传递一个函数有一个struct C++

这个问题是对结构的一种实践,它需要用户输入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; 
} 

回答

3

您需要返回学长:

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; 
} 
+0

我真的很感谢,但我有一个小问题,编译器现在突出显示在行“”Max“之前的操作数”“Max <<”是更老的学生“<< endl; “因为没有操作符匹配这些操作数,这意味着什么以及如何纠正这个错误? – Nashat12

+0

你没有为你的结构提供'operator <<'重载,所以'cout'不知道如何输出它无论是重载'operator <<'还是单独输出成员 –

0

的问题是,在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); 
+0

我真的很感谢,但我有一个小问题,现在编译器突出显示了行“”中的最大值之前的操作数“”\t cout << Max <<“是较老的学生”<< endl“,因为没有操作符匹配这些操作数。这是什么意思,以及如何纠正这个错误? – Nashat12

+0

这是因为打印名称而发生的,您试图打印学生本身。只需将“Max”替换为“Max.name”即可使用。 –

相关问题