新微赢技术网

标题: [求助]指针问题 [打印本页]

作者: ˊ.龙之吻︷    时间: 2009-11-4 02:03
标题: [求助]指针问题
//建立一个对象数组,内放5个学生数据,用指针指向首元素,输出第1,3,5个学生的数据
#include <iostream>
using namespace std;
class Student
{ public:
Student(int,int);

private:
int num;
int score;
};
Student::Student(int n,int s):num(n),score(s){}
int main()
{ Student a[5]={
Student(1,70),
Student(2,65),
Student(3,80),
Student(4,90),
Student(5,75)
};
int i;
int *p=&a[];
for(i=0;i<5;i++)
if(i%2==0)
p=p->a[i];
cout<<*p<<endl;
return 0;

}
21 D:\Dev-Cpp\program\cpp3.cpp expected primary-expression before ']' token
24 D:\Dev-Cpp\program\cpp3.cpp `a' is not a type
24 D:\Dev-Cpp\program\cpp3.cpp request for member of non-aggregate type before '[' token




用函数指向数组首元素怎么写啊? 改了好多次都不行
帮忙改下!!!谢谢
作者: 老鼠爱上猫    时间: 2009-11-4 02:03
#include <iostream>
using namespace std;
class Student
{
public:
Student(int n,int s)
{
num = n;
score = s;
}
void Print()
{
cout<<"num ="<<num<<endl;
cout<<"socre ="<<score<<endl;
}
private:
int num;
int score;
};
int main()
{
Student a[5]={
Student(1,70),
Student(2,65),
Student(3,80),
Student(4,90),
Student(5,75)
};
int i;
Student *p;
p = a;
for(i=0;i<5;i++)
if(i%2==0)
(p+i)->Print();
return 0;

}
作者: 月半弯    时间: 2009-11-4 02:03
二楼说的对。顶~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
作者: 假tp老tp练    时间: 2009-11-4 02:03
#include <iostream>
using namespace std;
class Student
{ public:
Student(int,int);

private:
int num;
int score;
};
Student::Student(int n,int s):num(n),score(s){}
int main()
{ Student a[5]={
Student(1,70),
Student(2,65),
Student(3,80),
Student(4,90),
Student(5,75)
};
int i;
Student *p=a;
for(i=0;i<5;i++)
if(i%2==0)
p=&a[i];
cout<<p<<endl;
return 0;

}
作者: 女装批发3    时间: 2009-11-4 02:03
#include <iostream>
using namespace std;
class Student
{ public:
Student(int,int);
int getsum()
{return num;}
int getscore()
{return score;}//private 变量要通过成员函数和友元函数访问
private:
int num;
int score;
};
Student::Student(int n,int s):num(n),score(s){}
int main()
{ Student a[5]={
Student(1,70),
Student(2,65),
Student(3,80),
Student(4,90),
Student(5,75)
};
int i;
Student *p=a;
for(i=0;i<5;i++)
if(i%2==0)
//p=&a[i];
cout<<a[i].getscore()<<' '<<a[i].getsum()<<endl;
return 0;

}
//21 D:\Dev-Cpp\program\cpp3.cpp expected primary-expression before ']' token
// 24 D:\Dev-Cpp\program\cpp3.cpp `a' is not a type
//24 D:\Dev-Cpp\program\cpp3.cpp request for member of non-aggregate type before '[' token

// 用函数指向数组首元素怎么写啊? 改了好多次都不行
// 帮忙改下!!!谢谢
作者: 蓳隯Д麞帥    时间: 2009-11-4 02:03
对于一维数组第i个元素的地址为:&a[i] 或a +i;
数组的首地址可以这样表示:a 或 &ap0];
数组名a代表的就是元素a[0]的地址,即&a[0]。
作者: ぱホ    时间: 2009-11-4 02:03
hehe ,楼上的都对,这个问题比较容易。
主要是关于数组名,首地址,等问题的注意
我就不多多废话了
作者: 五龙    时间: 2009-11-4 02:03
学习中




欢迎光临 新微赢技术网 (http://bbs.weiying.cn/) Powered by Discuz! X3.2