C++类对象指针作为函数参数应用的问题
书上有个题:建立一个对象数组,内放5个学生的数据(学号、成绩),设立一个函数max,用指向对象的指针作函数参数,在max函数中找出5个学生中成绩最高者,并输出其学号。
对于这个问题,本小白调试了好久,也没想明白这个学号最后怎么输出……
也许是我思路有问题,请各位大牛给个思路,看我下面那代码,我真心不知道这max怎么写,又是怎么调用?
#include <iostream>
using namespace std;
class Student
{
public:
Student(int a,int b);
void max(Student * x);
private:
int num;
int score;
};
Student::Student(int a,int b):num(a),score(b)
{}
void Student::max(Student * x)
{
for(int i=0;i<=4;i++)
{
if(x->score>(x+1)->score)
{
(x+1)->score=x->score;
}
}
cout<<(x+1)->num<<'\t'<<(x+1)->score<<endl;
}
int main()
{
Student st[5]={Student(10,89),Student(11,90),Student(12,91),Student(13,93),Student(14,94)};
//怎么调用那个max?
return 0;
}
void max(Student * x)
{
for(int i=0;i<=4;i++)
{
if(x->score>(x+1)->score)
{
(x+1)->score=x->score;
}
}
//复制你的算法代码,没有测试对否!
cout<<(x+1)->num<<'\t'<<(x+1)->score<<endl;
}
}
}
*/
void max(Student * x)
{
for(int i=0;i<=4;i++)
{
if(x->score>(x+1)->score)
{
(x+1)->score=x->score;
}
}
//复制你的算法代码,没有测试对否!
cout<<(x+1)->num<<endl;
cout<<(x+1)->score<<endl;
}
int main()
{
Student st[5]={Student(10,89),Student(11,90),Student(12,91),Student(13,93),Student(14,94)};
//怎么调用那个max?
max(st);
return 0;
}
这样就对了。。。你看看行不
[解决办法]
#include <iostream>
using namespace std;
class Student
{
public:
Student(int a,int b);
static Student max(Student stu[]);
inline int getScore( void )
{
return score;
}
inline int getNumber( void )
{
return num;
}
private:
int num;
int score;
};
Student::Student(int num,int score)
:num(num),score(score)
{
}
Student Student::max(Student stu[])
{
Student maxStu = stu[0];
for ( int index = 1; index < 5; ++index )
{
if ( maxStu.score < stu[index].score )
{
maxStu = stu[index];
}
}
return maxStu;
}
int main()
{
Student stu[5]={Student(10,89),Student(11,90),Student(12,91),Student(13,93),Student(14,94)};
Student maxStu = Student::max( stu );
cout << " Max Score: " << maxStu.getScore() << " The Stu Number: " << maxStu.getNumber() << endl;
return 0;
}