2、建立一个对象数组,内放6个学生的数据(学号、成绩),用指针指向数组首元素,输出2,4,6个同学的数据。
#include <iostream>
using namespace std;
class Student{
public:void get_student();
void display();
private:int num;int score;
};
void Student::get_student(){
cin>>num>>score;
}
void Student::display()
{cout<<"num="<<num<<"\t"
<<"score="<<score<<endl;
}
int main(){
int i;
Student *p;
p=new Student[6];
Student *t = p;
for(i=0;i<6;i++)
{
cout<<"请输入第"<<i+1<<"名学号和成绩:";
p->get_student();
p++;
}
cout<<"输出第2.4.6个学生的数据:\n";
p=t;
p++;
for(i=0;i<6;i=i+2)
{
p->display();
p=p+2;
}
delete []p;
delete []t;
return 0;
}
4、建立一个对象数组,内放6个学生的数据(学号、成绩),设立一个函数max,使用对象指针作为函数参数,在max函数中找出6个学生中成绩最高者,并输出其学号。
#include <iostream>
using namespace std;
class Student
{
public:
Student(int = 0,int = 0);
void display();
void max(Student * ,int);
private:
int no;
int score;
};
Student::Student(int no,int score):no(no),score(score){}
void Student::display()
{
cout <<"no:" << no << " score:" << score << endl;
}
void Student::max(Student * stu,int n)
{
Student *max_stu = stu;
for (int i = 0; i < n; i++)
{
if ((*stu).score > (*max_stu).score)
{
max_stu = stu;
}
stu++;
}
(*max_stu).display();
}
int main()
{
Student stu[6] =
{
Student(1,100),
Student(2,200),
Student(3,300),
Student(4,400),
Student(5,500),
Student(6,450)
};
Student *p;
p = stu;
(*p).max(p,6);
system("pause");
return 0;
}