2-1 什么是对象?
导向:Oriented
从对象出发考虑、解决、分析问题。
对象:object = entity(东西,实体) 。什么都是东西。可能是可见也可能是不可见。
在程序设计语言中,对象就是变量。int i
变量用来保存数据,变量的类型决定变量能保存什么样的数据。
对象 = 属性 + 服务
-
data:the properties(性质) or status(身份),被保护起来
-
operations(操作):函数,提供服务
不要直接去操作内部的数据。
写程序为了解决问题,过程就是把问题用程序描述出来。从问题空间到程序空间的映射。
C语言的程序是 事情发生的流程是什么?面向过程。时间顺序分析事情。
面向对象是在一个场景里面有什么东西,它们之间的关系是什么。
C语言设计一个三维坐标点
typedef struct point3d{
float x;
float y;
float z;
} Point3d;
void Point3d_print(const Point3d* pd);
Point3d a;
a.x=1;
a.y=2;
a.z=3;
Point3d_print(&a);
C++版本
class Point3d{
public:
Point3d(float x,float y,float z);
print();
private:
float x;
float y;
float z;
};
Point3d a(1,2,3);
a.print(); // 对象.函数 . 运算符
c的struct中只有数据,c++的class中既有数据还有操作。
c的操作是在结构体的外面的,你要让它做什么事情需要传它的指针进去。
c++操作是结构体内部当你要做什么操作你让那个结构自己去做那个操作,而不是要把那个地址传到一个函数当中去
C++最初的版本:在c的基础上做了class的东西
什么是Object-Oriented ?
- 一种方法来组织
- designs(找到问题的思路,办法) 与编程语言无关
- implementations(实现,代码) 面向对象的语言可以用来实现,面向对象的思想可以来设计。
- 对象,而不是控制或数据流,是我们设计和实现主要关注的。
- to focus on tings,not operation
2-2 Object-Oriented 基本概念
对象是互相之间在发送和接收消息。
objects send messages
- messages are
- composed(组合) by the sender
- interpreted(解释,说明) by the receiver(执行由接收者自己决定做不做)
- implemented(执行) by methods
接收者如果没有提供那个需要的服务,不要直接操作内部的数据。消息以函数来实现。
- messages
- may cause receiver to change state
- may return results 反馈结果
object vs. class
- objects(cat)
- represent(表示) things ,events,or concepts
- respond to messages at run-time
- classes(cat class)
- define properties(性质) of instances
- act like types in c++
- fish is fish,bird is bird(物以类聚,人以群分)
实体和概念的关系。
OOP characteristics
- everting is an object
- a program is a bunch of objects telling each other what to do by sending messages(程序是一堆对象,这些对象以发送消息的方式告诉每个需要做什么) C语言是函数的集合,全局变量。 what to do 接收者自己决定做不做。
- each object has its own memory(内存) made up of other objects 对象内部是对象
- every object has a type(先有类型后有东西,计算机科学是人为的科学,区别于大自然)
- all objects of a particular type can receive the same messages(正过来:所有相同类型的对象可以接收相同的消息,反过来理解:能接受相同消息可以被认为是同一类东西)
an object has an interface(接口)
- the interface is the way it receives messages
- it is defined in the class the object belong to 接口定义了该对象属于什么类
接口的作用
- communication(通信,交流)
- protection(保护)
低耦合
隐藏实现
- inner part of an object,data members to present its state,and the actions it takes when messages is rcvd hidden
- class creators vs. client programmers
- keep client programmers' hands off portions they should not touch
- allow the class creators to change the internal(内部的) working of the class without worrying about how it will affect the client programming
encapsulation(封装)--- capsule(胶囊)不是打包
- bundle(捆) data and methods dealing with these data together in an object
- hide the details of the data and the action
- restrict only access to the publicized