C++高手进来啊 菜鸟问个程序

来源:百度知道 编辑:UC知道 时间:2024/06/04 17:35:30
#include<iostream>
using namespace std;
class Student//声明一个类
{
public:
Student(int n,float s):num(n),score(s){}
private:
int num;
float score;
};
int main()
{
Student stud[5]={Student(101,78.5),Student(102,85.5),
Student(103,98.5),Student(104,100.0),Student(105,99.5)};
cout<<*(stud).score<<endl;//经过调试 感觉这步出现了问题
getchar();
return 0;
}

score是private的,不能直接在外部使用,要么提供Student的类成员函数,要不改成public的成员。
*(stud).score,这里要改成(*stud).score,这是因为.和*的优先级问题,这样才能取到stud数组和第一个元素,也可以写成stud->score,或者stud[0].score。后者用下标的方式可读性更高

score是private成员,不能直接访问

score 是类 的私有成员变量
在外部调用当然抱错了

//类 public:
float getScore(){return score;}
//main
cout<<(*stud).getScore<<endl;//