注册 登录
编程论坛 C++教室

为什么不能这样啊?

boyyang4894 发布于 2007-02-23 15:59, 569 次点击

#include<iostream>
using namespace std;

class Student
{ public:
Student(int n,int a,float s):num(n),age(a),score(s){}
void total();
static float average();
friend void show(Student&);
private:
int num,age;
float score;
static float sum;
static int count;
};

void Student::total()
{ sum+=score;
count++;
}
float Student::average()
{ return (sum/count);}

void show(Student&t)
{
cout<<"the intformating of student is:"<<endl<<t.num<<endl<<t.age<<endl<<t.score<<endl;

}
int Student::count=0;
float Student::sum=0;
int main()
{ Student stud[3]={Student(120,22,100),Student(119,22,89),Student(118,23,60)};
int n;
cout<<"please enter the number of students:"<<endl;
cin>>n;
for(int i=0;i<n;i++)
stud[i].total();
cout<<"the average score of"<<n<<"students is:"<<endl<<Student::average()<<endl;
for(int j=0;j<n;j++)
show(stud[j]);// 为什么不能这么做啊?我编译时进入了死循环.只有把两个for改为for(int i=0;i<n;i++){stud[i].total();show(stud[i]);}就可以了,为什么啊,谁能告诉我.谢谢
system("pause");
return 0;
}


7 回复
#2
boyyang48942007-02-23 16:53
难道没有人知道么?
#3
dlcdavid2007-02-23 17:07

可以运行得嘛

[此贴子已经被作者于2007-2-23 17:29:58编辑过]

#4
dlcdavid2007-02-23 17:12

............

[此贴子已经被作者于2007-2-23 17:30:20编辑过]

#5
boyyang48942007-02-23 17:33
难道我的VC++有错?
#6
deng19872007-02-26 21:31
正常阿,你写的没问题阿,我试过了
#7
wfpb2007-03-02 23:30

你的想法和你的做法有点出路:
你想用static变量来记录学生个数和学生成绩总分,但是却用total函数来做,这样虽然可以但是比较麻烦。
我给一种稍微简单点的做法:


#include<iostream>
using namespace std;


class Student
{
    int num,age;
    float score;
public:
    Student(int n,int a,float s):num(n),age(a),score(s)
    {
        count++;
        sum+=score;
    }
    friend void show(Student&);
    static float average();
    static float sum;
    static int count;
};
float Student::average()
{
    return (sum/count);
}
void show(Student&t)
{   
    cout<<\"the intformating of student is:\"<<endl<<t.num<<endl<<t.age<<endl<<t.score<<endl;
}

int Student::count=0;  
float Student::sum=0;
int main()
{
    Student stud[3]={Student(120,22,100),Student(119,22,89),Student(118,23,60)};
    cout<<\"The average score of\"<<Student::count<<\"students is:\"<<endl<<Student::average()<<endl;
    for(int j=0;j<Student::count;j++)
        show(stud[j]);
    system(\"pause\");
    return 0;
}
注意:未编译,请自行编译调试

[此贴子已经被作者于2007-3-2 23:33:24编辑过]

#8
boyyang48942007-03-10 22:05
看到了,谢谢
1