5对象和类

第5章 对象和类 5.1 过程性编程和面向对象编程 面向对象编程是一种设计程序的概念性方法,它的主要特点如下: 抽象 封装和数据隐藏 多态 继承 代码的可重用性 例如,用计算机统计一个篮球队中各球员的技术数据 面向过程的程序员: 要输入球员的姓名,投篮次数,命中率等重要数据,其中一些数据如命中率由计算机来计算 程序能够显示这些数据 让main函数调用一个函数来实现输入,再调用一个函数来实现计算,调用第三个函数显示结果。下一场比赛呢?可以再用一个函数更新统计数据。Main函数中需要放一个菜单,以让用户选择输入,计算,显示结果或更新数据 表示数据:用数组或结构 总之,首先考虑要遵循的步骤,然后考虑如何表示数据 面向对象的程序员如下考虑: 我要跟踪的是球员,要有一个对象表示选手的姓名和各种统计数据 需要一些方法:首先是把基本信息加入到这些单元中去----初始化;需要一些计算方法,如命中率,程序应自动执行这些方法,无需用户干预;更新和显示信息的方法 所以,用户和数据交互的方式有三种:初始化,更新和报告----用户接口 总之,使用面向对象的方法时首先从用户的角度考虑对象----描述对象所需的数据以及描述用户与数据交互所需的操作。 提倡多文件的程序结构 文件是程序的编译单位,可以实现单独编译 一个文件修改后不用重新编译整个程序,有利于大程序的管理 有利于程序的安全,是封装的一种手段,把实现细节与抽象分开 程序的结构更清晰 头文件中常包含的内容: 函数原型 符号常量(用#define或const定义) 结构声明 类生明 模板声明 内联函数(普通函数定义不可) OOP通常的做法是一个头文件中放置类定义,另一个文件(源文件)放置类中方法的定义 一个坐标转换的例子: // coordin.h -- structure templates and function prototypes // structure templates #ifndef COORDIN_H_ #define COORDIN_H_ struct polar { double distance; // distance from origin double angle; // direction from origin }; struct rect { double x; // horizontal distance from origin double y; // vertical distance from origin }; // prototypes polar rect_to_polar(rect xypos); void show_polar(polar dapos); #endif // file1.cpp -- example of a three-file program #include iostream #include coordin.h // structure templates, function prototypes using namespace std; int main() { rect rplace; polar pplace; cout Enter the x and y values: ; while (cin rplace.x rplace.y) // slick use of cin { pplace = rect_to_polar(rplace); show_polar(pplace); cout Next two numbers (q to quit): ; } cout Bye!\n; return 0; } // file2.cpp -- contains functions called in file1.cpp #include iostream #include cmath #include coordin.h // structure templates, function prototypes // convert rectangular to polar coordinates polar rect_to_polar(rect xypos){ using namespace std; polar answer; answer.distance = sqrt( xypos.x * xypos.x + xypos.y * xypos.y); answer.a

文档评论(0)

1亿VIP精品文档

相关文档