文档详情

面向对象程序设计语言C++第03章_类与对象.ppt

发布:2017-03-21约5.6千字共37页下载文档
文本预览下载声明
class Circle private: int x, y; //圆心的X、Y坐标 float fRadius; //半径 public: void SetXY int a,int b ; void SetRadius float r ; void Move int newx,int newy ; … //其它成员 ; 类的使用 void main Date today;yourbirth,oneday; today. InitDate 24,9,2008 ; yourbirth. InitDate 12,7,1990 ; Date * poneday; poneday oneday; poneday- InitDate 26,9,2008 ; … 将整数作为对象 class INT int numb; public: void Set int n numb n; void Get return numb ; … ; void main INT oneINT;twoINT; oneINT.Set 1 ; twoINT.Set 10 ; cout oneINT.Get twoINT.Get ; 问题:成员函数如何“知道”对哪个对象的数据进行操作? this class INT int numb; public: void Set int n ,INT * const this this- numb n; void Get INT * const this return this- numb ; … ; void main INT oneINT;twoINT; oneINT.Set 1,oneINT ; twoINT.Set 10,twoINT ; cout oneINT.Get oneINT twoINT.Get twoINT ; 例仓库管理中,假定只关心货物的重量,可以使用static数据表示总重量。 #include using namespace std; class Goods private: float fWeight; static float fTotalWeight; public: void AddGoods float weight fWeight weight; fTotalWeight + weight; void RemoveGoods fTotalWeight - fWeight; void ShowWeight cout fWeight endl; void ShowTotalWeight cout fTotalWeight endl; //直接访问static数据 ; float Goods::fTotalWeight 0.0; //static 成员的定义及初始化 void main Goods goods1, goods2, goods3; goods1.AddGoods 100 ; goods2.AddGoods 70 ; goods3.AddGoods 150 ; goods2.ShowWeight ; goods1.ShowTotalWeight ; 输出结果为: 70 320 第三章 类和对象 3.2 类的成员 3.2.3 静态成员 静态数据成员 在一个类中,若将一个数据说明前加上static,则该数据称为静态数据。 静态数据成员被该类的所有对象共享。无论建立多少个该类的对象,都只有一个静态数据的存储空间。 * 第三章 类和对象 3.2 类的成员 类aClass包括一个普通数据成员anInt和一个静态数据成员anSint。 假设定义了三个对象A、B和C。 * Object A int anint; Object B int anint; Object C int anint; static int sint; 第三章 类和对象 3.2 类的成员 静态数据成员的存储空间必须在类定义外进行分配,具体的语法如下: 类型名 类名::静态数据成员 [ 常量表达式 ]; 定义时为他们做初始化工作是必须的。 * 第三章 类和对象 3.2 类的成员 3.2.3 静态成员 静态数据成员 静态数据成员属于类,而不属于对象。 静态数据成员也分为公有和私有的, 在类外只能访问公有的静态数据成员,且访问方式为: className::staticMember * 第三章 类和对象 3.2 类的成员 3.2.3 静态成员 静态函数成员 成员函数也能被说明为静态的。 与静态数据成员一样,静态成员函数属于类而不是某个类对象
显示全部
相似文档