C++面向对象编程入门:类(class)(2)
gradescore = (goodball*gbs + badball*bbs) / (goodball + badball);
return gradescore; //返回平均成绩
}
};
主函数调用:
#include <iostream>
#include "ballscore.h"
using namespace std;
void main()
{
ballscore jeff;
cout<<jeff.GetGS(10,3);
jeff.gradescore=5.5//想篡改jeff的平均成绩是错误的!
cin.get();
}
在上面的代码中头文件和类的使用很好了体现了类的黑盒特性,谁也不能够在外部修改球员的平均成绩!
类体中的有一个地方要注意
const static int gbs = 5;//好球单位得分
const static int bbs = -3;//坏球单位扣分
之所以要修饰成const static 因为c++中类成员只有静态整形的常量才能够被初始化,到这里整个程序也就说完了,当然真正大比赛不可能是这样,只是为了说明问题就题命题而已,呵呵!
下面我们说一下关于类的作用域。
在说内容之前我们先给出这部分内容的一个完整代码,看讲解的是参照此一下代码。
#include <iostream>
using namespace std;
class ballscore
{
protected:
const static int gbs = 5;//好球单位得分
const static int bbs = -3;//坏球单位扣分
float gradescore;//平均成绩
public:
float GetGS(float goodball,float badball) //goodball为好球数量,badball为坏求数量
{
int gradescore=0;
- 最新评论
