01 面向对象

本文详细介绍了面向对象的基本原理,包括对象作为编程语言中的变量、消息传递机制、封装概念以及C++中的实现。讲解了对象的构成、接口的作用、变量声明与定义的规则,并通过实例展示了对象内部成员变量和局部变量的区别。此外,还探讨了C++的编译过程和命名规则,以及头文件的防重复包含策略。
摘要由CSDN通过智能技术生成

面向对象基本原理 相关英文

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

image-20211014104246084

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;

.hdeclaration 和 .cppdefinition 总是成对出现

编译过程

xxxx.cpp----预编译—> xxxx.i编译—>xxxx.s(汇编代码) ----汇编—> xxxx.o (目标代码)—链接—> xxxx.out

编译单元是一个.cpp文件

cpp编译器(g++)会改变变量名字 :加上下划线 _

编译预处理指令 cpp
g++ 编译时 添加指令 --save-temps 会保存临时文件

保持临时文件hello.ii预编译hello.s汇编代码

域的解析符 ::

  • <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

  1. 一个 .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 的地址一样

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值