在程序中传递功能具有结构C
passing a function in a program has a 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;
}
您需要退还年长的学生:
student getOlder(student s1, student s2)
{
if (s1.age > s2.age)
{
return s1;
}
return s2;
}
另外,由于您没有更改s1
或s2
的内容,因此应将它们作为常量参考传递:
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期间设置等于s1
或s2
:
student result;
if(s1.age>s2.age){
result=s1;
}else{
result=s2;
}
return result
,或者您可以跳过result
部分,然后退还学生:
if (s1.age > s2.age)
{
return (s1);
}
return(s2);
相关文章:
- C++中用于结构的纯数组的类似于TableView/DataFrame的通用功能
- 对于没有功能的结构,"new (ptr) mystruct;"做什么?
- 在C 中,是否有树木数据结构具有相似的功能
- 如何使用结构内的功能指针调用私有函数
- C++要在其中添加接口功能的类层次结构
- 获得const结构和CIN的功能
- 访问嵌套结构的数据成员并将结构传递到功能C
- 在C 功能执行后,使用GCHANDLE CRALSES将大型结构从C#Unity脚本传递到C DLL
- 调用功能并将其设置为等于结构
- 在模板功能中打印任何结构
- MPI_Op_create:候选功能不可行.自定义结构指针不能解释为空指针
- 创建结构并传递IT功能
- 从公共功能原型中获取私有结构
- 在程序中传递功能具有结构C
- 局部结构通过使用共同的模板功能来影响不同的翻译单元
- 导入C 功能将结构的指针返回到VB.NET中
- 有关继承层次结构的问题,没有任何虚拟功能
- 如何从另一个功能中修改的结构的炭指针成员中获取值
- 对具有继承功能的结构使用初始值设定项列表
- 结构功能有问题