建立一个对象数组,内放5个学生的数据,用指针指向数组首元素,输出第1,3,5个学生的数据

#include<iostream>
using namespace std;
class Student
{public:
Student(int n,float s):num(n),score(s){}
void display();
private:
int num;
float score;
};
void Student::display()
{cout<<num<<" "<<score<<endl;};
int main()
{
Student stud[5]={Student(1002,78),Student(1004,89),Student(1005,78),
Student(1007,85),Student(1008,90)};
Student *p=stud;
for(int i=0;i<=2;p=p+2,i++)//p=p+2这个我有少少不明白,前面是i=0;i<2是指向的范围,p=p+2是指向是对象,但是如果p为0时(0+2=2),p为1时(1+2=3),p为2时(2+2=4),这样就不是指向1、3、5的学生了,大家帮忙一下。
p->display();
return 0;
}

第1个回答  2012-09-30
1、3、5不是数组下标
换成数组下标为 0、2、4
通俗点说就是数组的第一个元素的下标为零,第二个下标为一,以此类推。
还有,for循环写的不够简洁本回答被提问者采纳
第2个回答  2012-09-30
stud[5]是一个数组存放第0个到第4个学生(0-4,共5个)的信息。

p=stud;这样p指向的是第0个,每次循环p=p+2,则在接下来的两次内,p分别指向第2个,第4个学生。

如果从1开始编号(1-5)的话,也就是你说的1、3、5号学生了。
第3个回答  2012-09-30
我不清楚你说的。我解释下代码吧。i=0,p指向stud[0],i=1,p指向stud[2],i=2,p指向stud[4],因此打印第1、3、5学生的信息追问

i=0,p指向stud[0],i=1,p指向stud[2],i=2,p指向stud[4],但是你都需要一个条件吧,如果按你这样说,p=p+2这个条件都不需要用到了,直接删掉。

本回答被网友采纳
第4个回答  2012-09-30
没错吧 我感觉你写的没什么错
相似回答