面向对象程序设计C++

简介: 面向对象程序设计C++

2 什么是对象?

What is an object?

对象 = 东西

Object = Entity

所有东西都是对象

对象可以是可见的or不可见的

Object may be

-Visable or

-Invisible

在编程中,对象是变量。

Object is variable in programming languages

对象 = 属性 + 服务

Objects = Attributes + Services

|-----------|  

|Operations |

|           |

||----|     |

||Data|     |

||----|     |

|-----------|

数据(受保护)

Date:the properties or status

操作:功能or接口

Operations:the functions

什么  是  面向对象?

What  is object-oriented

一种方式去组织

A way to organize

 设计

 Designs

 实现

 Implementations

对象,而不是控制or数据流,是设计首要关注的东西

Objects,not control or data flow, are the primary focus of the design and implementation.

关注事物,而不是操作

To focus on things, not operations.  

3 面向对象基本原理

Object Oriented Programming

对象发送和接受消息

Objects send and receive 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

Object(实体)

Represent things,events, or concepts

Respond to messages at run-time


Class (概念)

定义属性

Define properties of instance

Act like types in C++

Class defines Object

Object is a  Class

OOP Characteristics

1.Everything is an object.

2.A program is a bunch of objects telling each other what to do by sending messages.

2.程序是一堆对象,以发送信息形式告诉彼此做什么(而不是怎么做)。

3.Each object has its own memory made up of other objects.

3.每个对象有自己的内存,由其他对象组成。

4.Every object has a type

4.任何对象都有类型

5.All objects of a particular type can receive the same messages

5.特定类型的所有对象都能接受相同消息

(能接受相同消息的对象可以看成同一类)


对象有接口

An object has an interace

接口是获取它得到消息的方法。

The interface is the way it receives massages.

接口定义了对象所属的类。

It is defined in the class the object belong to.

Functions of the interface

Communication

Protection

The hidden implementation

Inner part of an object,data members to present its state, and the actions it takes when messages is rcvd is hidden.

Class creator vs Client programmers

-不让使用者碰到不该碰的东西

-让制造者能改变内部而不影响使用者的使用。

-Keep client programmers'hands off portions they should not touch.

-Allow the class creator to change the internal working of the class without worrying about how it will affect the client programmers.

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

7 成员变量

local variable

本地变量

Fields,parameters,local variables

成员变量,参数,本地变量

All three kinds of variable are able to store a value that is appropriate to their defined type.

都能存储值。

Fields are defined outside comstructors and methods.

成员变量和函数无关。

Fields are used to store data that persists throughout the life of an object. as such, they maintain the current state of an object. They have a lifetime that lasts as long as their object lasts.

成员变量存在,只要对应的对象存在。


Fields have class scope:their accessibility extends throughout the whole class,and so they can be used within any of the constructor or methods of the class in thich they are defined.

成员变量有类作用域:在整个类都可用。

this:the hidden parameter

this is a hidden parameter for all member functions, with the type of the class

9.构造与析构

Guranteed initialization with the constructor

使用构造函数保证正确初始化

If a class has a constructor, the compiler automatically calls the constructor at the point an object is created, before client

programmers can get their hands on the object.

编译器在对象创建时自动调用构造函数。

The name of the constructor is the same as the name of the class.

构造函数和类同名。


Constructors with arguments

构造函数可以有参数。

Tree(int i) {...}

调用:

Tree t(12);


The destructor

析构函数

(对象消失时调用)

In C++,clean up is as important as initialization and it therefore guaranteed with the destructor.

The destructor is named after the name of the class with a leading tilde(~).The destructor never has any arguments.

析构函数名是 :在类名前加~,

析构函数不能有参数。


When is a destructor called?

The destructor is called automatically by the compiler when the object goes out of scope.

对象离开scope时调用析构函数。

The only evidence for a destructor call is the closing brace of the scope that surrounds the object.

11 new & delete

Dynamic memory allocation

new

new int; new Stash; new int [10];

delete

delete p; delete[] p;

new and delete

new is the way to allocate memory as a program runs.Pointers become the only access to that memory

new是在程序运行期间分配内存的一种方式。指针是访问new分配的内存的唯一方式。

delete enables you to return memory to the momory pool when you are finished with it.

delete返回内存到内存池中。


Dynamic Arrays


int * psome = new int [10];


The new operator returns the address of the first element of the block.


delete[] psome;

The presence of the brackets tells the program that it should free the whole array,not just the element.


Tips for new and delete

Don't use delete to free memory that new didn't allocate.

不要用delete删除不是new分配的空间。

Don't use delete to free the same block of memory twice in succession.

不要连续delete一块空间两次

Use delete[] if you used new[]

to allocate an array.

Use delete if you used new to allocate a single entity.

delete和new应该配套。

it's safe to apply delete to the null pointer(noting happens) .

可以delete null指针

12.访问限制

Setting  limits

to keep the client programmer's hands off members they shouldn't touch.

to allow the library designer to change the internal workings of the structure without worrying about how it will affect the client programmer.


C++ access control

-public 公开,任何人

-private 私有,仅自己(还有friends)

-protected 保护,自己和子类


friends

可以是函数or类


class vs. struct

class  默认 private

struct 默认 public

14.对象组合

Reusing the implementation

软件重用

Compostion:construct new object with existing objects

组合:用已有对象来创建新对象

It is a relationship of "has-a"

是一种 包含 的关系。

-------------------------|

|car                     |

|                        |

|-------   ------        |

|engine|   |tyre|        |

|-------   ------        |

|------------------------|


Composition

15继承

Reusing the interface

Inheritance is to take the existing class,clone it and then make additions and modifications to the clone.

Inheritance

Language implementation technique

Also an important component of the OO design methodology

Allows sharing of design for

-Member data

-Member functions

-Interfaces

数据、功能、接口共享

Key technology in C++

Interface

Class relationship :Is-A

16子类父类关系

constructor

Base class is always constructed first

If no explicit arguments are passed to base class ,Default constructor will be called

Destructors are called in exactly the reverse order of the constructors.

基类构造函数先调用。

析构函数调用顺序和构造函数相反。

18 内联函数

Inline functions

An inline function is expanded in place, like a preorocessor macro, so the overhead of the function call is eliminated.

调用inline函数时并不真的调用函数,而是把函数代码嵌入。

inline int plusOne(int x);

inline int plusOne(int x){return ++x;};


Repeat inline keyword at declaration and definition.

inline函数的inline关键字要重复出现在声明和定义中

An inline function definition may not generate any code in .obj file.



Inline functions in header file

Can put inline functions'bodies in header file.

Never be afraid of multi-definition of inline functions,since they have no body at all.

Definition of inline functions are just declarations.


inline 函数

是一种以空间换时间的策略


Inline inside class

class成员函数 给出了函数体实际上是inline


19 const

Constants are variables

const 变量 是变量


Pointers and const


char * const q ="abc"//q is const

const char *p = "ABCD";

//(*p) is a const char

const在:

*后面 指针是const

*前面 对象是const


Passing and returning addresses

Passing a whole object may cost you a lot.it is better to pass by a pointer.

But it's possible for programmer to take it and modify the original value.

In fact, whenever you're passing an address into a function, you should make it a const if at all possible.

传地址节省资源。

防止原来的值被修改可以在传参数前加const.

21 引用

Declaring references


引用在定义时要(用变量)初始化

type& refname = name;

建立一种绑定关系

绑定之后不能变


引用也叫别名


References vs. Points


Referfences

can't be null

are dependent on an existing variable,they are an alias for an variable

can't change to a new "address" location


Pointers

can be set to null

pointers in independent of existing objects

can change to point to a different address


no

references to references

pointer to references

arrays of references


22.向上造型

如果B是A的子类,

B的对象可看成A的对象


即子类有所有父类的属性和函数。


Upcasting

Upcasting is the act of converting from a Derived reference or pointer to a base class reference or pointer.

23.多态性


Inheritance in C++

Can define one class in terms of another


Polymorphism

Upcast:take an object of the derived class as an object of the base one.

Dunamic binding:

Binding:which function to be called

S-tatic binding:call the function as the code

-Dynamic binding:call the function of the object

25.引用再研究


Referfencec as class members

Declared without value

Must be initialized using constructor initializer list

必须使用初始化列表


函数返回引用:

不要返回本地变量


26 拷贝构造

使用已经存在的对象来创建对象


拷贝构造 使用 拷贝构造函数


C++会提供默认的拷贝构造函数(如果自己没有写)

28 静态对象

Static in C++

Static local variables Persistent storage

Static member variables Shared by all isntances

Static member function Shared by all instance,can only access static member variables

静态局部变量: 持续的存储

静态成员变量: 所有的实例共享

静态成员函数:所有实例共享,只能访问静态成员变量


静态成员要在class外面进行初始化


34 模版1


模版的用处:

X,Y两种类型,要进行相似的操作


Reuse source code


Functions Template

函数模版

template<class T>

void sawp(T& x,T& y)

{

   T temp = x;

   x = y ;

   y = temp;

}


foo<int>()


Classes Template

template<class T>

class Vector

{

   public:

   Vector(int);

   ~Vector();

   ...

   T& operator[](int);

   ...

}


Usage

Vector<int> v1;



35模版2

template

可以有多个参数

可以有默认参数。


模版和继承

Templates and inheritance

模版可以继承模板类(具体的),也可以是类


36异常基本概念


Run-time Error

c++基本的哲学是“写的不好的代码不应该被运行”

但是总会在运行阶段发生一些事情,

处理这些可能发生的情况是很重要的。


E:read a file

打开文件,判断文件大小,分配空间,读入内存,

关闭文件。

这些步骤都可能出现问题。

try {

   ...

}catch( ){

   ...

}catch(){

   ...

}


exception

i take exception to that


At the point where the problem occurs,

you might not know what to do with it, but you do know that you can't just continue on merrily;you must stop, and somebody, somewhere, must figure out what to do.

遇到问题时不知道怎么办,需要停下来,等待解决、


exception最大是好处是有清晰的错误处理代码,将业务逻辑和错误处理分开。.

37异常的抛出和捕捉

throw 抛出(可以是任何东西,通常是对象)

如何抛出异常

...

...

if(index < 0 || index >= m_size)

   throw VectorIndexError(index);

 

控制会回到可以处理异常的地方


exception最常用的方面是输入、输出。

39流的概念

streams

C++通过流进行输入输出,文件操作

流能够提供更好的类型安全,可扩展,更面向对象。

缺点啰嗦,慢

c vs. c++

c的方法在c++能用

但是不能重载。

c++可以重载<<, >>


什么是流?

一维、单方向

标准库中的流

iostream

fstream


Stream 运算符

Extractors

从流读

>>

Inserters

写入流

<<

Manipulators

控制,改变流的状态

Others

流的类型

文本流Text streams

二进制流 Binary streams


40.流的运算符

istream >> value


自定义

istream& operator>>(istream& is, T& obj){

   //...

   return is;

}


int get()

cin.get()


istream& get(char& ch)


getline

ignore

gcount

putback

peek


inserters

<<

ostream & operator <<(ostream& os, const T& obj){

 

   return os;

}


put(char)

flush()

格式控制:

#include<iomanip>

cin>>hex>>n


setprecision(n)

setw(width)


Manipulators:

dec,hex,oct

endl

flush

setw(int)

setfill(ch)

setbase(int)

ws

setprecision(int)

setiosflags(long)

resetiosflags(long)


自定义manipulator

ostream& manip(ostream& out){

   ...

   return out;

}


ostream& tab( ostream& out){

   return out<<'\t';

}


Stream flags

ios::skipws

ios::left,ios::right

...

...

...


42STL简述

STL = Standard Template Library

标准模版库

可读性,强壮性


包括

容器 Vector

链表 List

集合 Sets

映射 Maps


基础算法


定义在std空间:using namespace std;


最常用的3种:

map

vector

list


例子:

#include<iostream>

#include<vector>

using namespace std;


int main()

{

   vector<int> x;

   for(int a=0; a<1000; a++)

       x.push_back(a);

   vector<int>::iterator p;

   for(p=x.begin();p<x.end();p++_

       cout<<*p<<" ";

   return 0;

}


相关文章
|
8天前
|
C++
C++ : 程序设计简单实例
C++ : 程序设计简单实例
13 3
|
8天前
|
安全 C++
C++:程序设计实例
C++:程序设计实例
11 2
|
20天前
|
C++
C++程序设计实践一上(题目来自杭州电子科技大学ACM)
C++程序设计实践一上(题目来自杭州电子科技大学ACM)
12 2
|
20天前
|
C++
C++程序设计实践一下(题目来自杭州电子科技大学ACM)
C++程序设计实践一下(题目来自杭州电子科技大学ACM)
16 1
|
22天前
|
算法 编译器 C语言
C++进阶之路:深入理解编程范式,从面向过程到面向对象(类与对象_上篇)
C++进阶之路:深入理解编程范式,从面向过程到面向对象(类与对象_上篇)
22 3
|
1天前
|
C++
技术经验分享:C++程序设计的技巧
技术经验分享:C++程序设计的技巧
|
10天前
|
C++
C++ 是一种面向对象的编程语言,它支持对象、类、继承、多态等面向对象的特性
C++ 是一种面向对象的编程语言,它支持对象、类、继承、多态等面向对象的特性
|
20天前
|
程序员 数据安全/隐私保护 C++
C++面向对象的四大特征
C++面向对象的四大特征
9 0
|
2天前
|
存储 编译器 C语言
【C++航海王:追寻罗杰的编程之路】类与对象你学会了吗?(上)
【C++航海王:追寻罗杰的编程之路】类与对象你学会了吗?(上)
7 2
|
1天前
|
C++
C++职工管理系统(类继承、文件、指针操作、中文乱码解决)
C++职工管理系统(类继承、文件、指针操作、中文乱码解决)
2 0
C++职工管理系统(类继承、文件、指针操作、中文乱码解决)