面向对象编程介绍
1.什么是面向对象
面向将系统看成通过交互作用来万恒特定功能的对象的集合。每个对象用自己的方法来管理数据。也就是说只有对象内部的代码能够操作对象内部的数据
2.面向对象的优点
通过,继承、封装、多态降低程序的耦合度,并结合设计模式让程序更容易修改和扩展,并且易于复用。
3.面向对象的特点
① 封装——维护性
② 继承——复用性
③ 多态——扩展性
④ 抽象
类与对象
1.类的声明
class Test
{
public:
公有成员(外部接口):对外可以访问
private:
私有成员:不能在类外访问
protect:
保护成员:不能在类外访问
};
2.成员函数
类内实现的方法默认为inline函数
Test.h
#ifndef _TEST_H_
#define _TEST_H_
class Test
{
pubilc:
int x_;
void initXYZ(int x, int y, int z);
void displayXYZ();
protected:
int y_;
private:
int z_;
};
Test.cpp
#include “Test.h”
#include <iostream>
void Teat::initXYZ(int x, int y, int z)
{
x_=x;
y_=y;
z_=z;
}
void Test:display()
{
cout x_<<”\ny_”<<”\nz_”<<endl;
}
Main.cpp
#include <iostream>
#include “Test.h”
int main()
{
Test t;
t.x_ = 5;
t.initXYZ(1,2,3);
t.displayXYZ();
return 0;
}
3.class VS struct
class数据成员默认私有
struct数据成员默认公有
class与struct一样遵循字对齐,大小只与成员有关,方法是共享在同一段空间中
4.对象的存储模型
this指针自动传参
Test *t1 = new Test();
t1->initXYZ(1,2,3);
调用时自动传输this指针,保存对象的地址
5.类的作用域
在A.h中调用B的类:
① 可用#include “B.h”
② 可以前向声明
A.h
#ifndef _A_H_
#define _A_H_
//#include "B.h"
class B;
class A
{
public:
A();
~A();
private:
B *b;
};
#endif
6.嵌套类(内部类)
class A
{
public:
int x_;
class Inner:
{
public:
int num;
func;
};
};
7.局部类
class LoclClass
{
func()
{
...........
}
};
局部类只在定义它的局部域内可见。
局部类的成员函数必须被定义在类体中
局部类中不能有静态成员