面向对象基本原理 相关英文
object is variable in programming languages ------ 对象在编程语言中是一种变量
对象发送和接受消息
message are
- composed by the sender // composed:创作
- interpreted by the receiver // interpreted:理解
- implemented by the methods // implemented:执行
sender 发生命令
接受者自己决定 执行或是不执行
object = attributes + services
An object has an interface
The interface is the way it receives messages
Functions of the interface ----- 接口的作用
- communication
- protection
Encapsulation: 封装
- 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 methods.
编码规范
对象:全小写 class:大驼峰(第一个单词的首字母也大写)
声明declaration和定义definition
declaration声明:
.h
表明变量的类型和名字- 主要有三部分
- extern variables
- function prototype
- class/struct declaration 注意: 不能重复声明class和struct
definition 定义:
-
.cpp
为变量分配存储空间 -
需要
#include "xxxx.h"
注意:int a; 属于定义。此时系统已经为a变量分配了内存空间
将
int a;
definition变成declaration 需要使用 extern 关键字extern int a;
.h
declaration 和 .cpp
definition 总是成对出现
编译过程
xxxx.cpp
----预编译—> xxxx.i
—编译—>xxxx.s
(汇编代码) ----汇编—> xxxx.o
(目标代码)—链接—> xxxx.out
编译单元是一个.cpp
文件
cpp编译器(g++)会改变变量名字 :加上下划线
_
编译预处理指令
cpp
g++ 编译时 添加指令--save-temps
会保存临时文件
域的解析符 ::
<class Name> :: <function name>
::<function name>
void Obj::func(){
::func(); // Would be recursive otherwise!
::a++; // Select the global a
a--; // The a at class scope
}
::
前面无类变量,则表示其后的func为全局函数
::a
使用全局变量 a
不加 ::
表示使用这个类的变量
头文件
标准头文件结构 —目的—>防止头文件被重复包含、防止class的重复声明
#ifndef HEADER_FLAG
#define HEADER_FLAG
//头文件内容
#endif
tips of header
- 一个
.h
放一个.class
在标准头文件结构中
成员变量和本地变量 (编译器就近原则
成员变量(field) :在对象中
本地变量:在函数/方法中
注意:若成员变量和本地变量同名,则使用本地变量(编译器的就近原则)
函数属于类,不属于对象
调用时类似 f(&a) 将a对象的地址传入到类 A 的方法 f() 中。用以确定是哪个对象调用的方法,同时对该对象进行相应操作
调用 a.f()
时 f()
是类的方法。
调用时类似 f(&a)
将对象a的地址传递给类的方法 f()
#include<stdio.h>
class Obj{
public:
char ch; // 有一个ch 但不在class类里面,它属于对象,在对象里面
Obj();
void func(); // func 在class类里面,不在对象里面
};
Obj::Obj(){
ch = 0;
printf("Obj::Obj() -- this=%p\n", this);
}
void Obj::func(){
this->ch = 20;
printf("Obj::func() -- &i=%p\n", &ch);
printf("Obj::func() -- this=%p\n", this);
}
int main(){
printf("Obj a;\n");
Obj a;
a.ch = 10;
printf("&a=%p\n", &a);
printf("&a.i=%p\n", &(a.ch));
a.func();
printf("==================\n");
printf("Obj b;\n");
Obj b;
printf("&aa=%p\n", &b);
b.func();
}
对象里面只有变量ch 故对象和变量ch的地址一样 (即 this 和 ch 的地址一样