面向对象编程的四大特性:
- 封装
- 抽象
- 继承
- 多态
封装
C++中,将数据和对数据的操作(函数)封装成一个叫“类(class)”的结构体。class Rectangle {protected:int width, height; //数据public:Shape(int a=0, int b=0){width=a;height=b;}int area() //对数据的操作{cout << "Rectangle::area()" << endl;return (width*height);} };- 继承
一个类可以继承另一个类,形成继承关系,又称父子关系。class Shape {protected:int width, height;public:Shape(int a=0, int b=0){width=a;height=b;}virtual int area() = 0; };class Rectangle:public Shape //Rectangle继承了Shape,Rectangle为子类/派生类,Shape为父类/基类 {public:Rectangle(int a=0, int b=0):Shape(a,b){}int area(){cout << "Rectangle::area()" << endl;return (width*height);} }; 多态
父类的(纯)虚函数被子类继承和重载,实现其特有的功能。不同的子类可以有不同的实现。这种现象称为多态。抽象
接口和实现分离,称为抽象。例如,父类的(纯)虚函数就是接口,子类对虚函数的重载为实现。#include <iostream> using namespace std;class Shape //抽象类 {protected:int width, height;public:Shape(int a=0, int b=0){width=a;height=b;}virtual int area() = 0; //接口 };class Rectangle:public Shape {public:Rectangle(int a=0, int b=0):Shape(a,b){}int area(){cout << "Rectangle::area()" << endl;return (width*height);} };class Triangle:public Shape {public:Triangle(int a=0,int b=0):Shape(a,b){}int area(){cout << "Triangle::area()" << endl;return (width*height)/2;} };int main() {Shape * shape;Rectangle rec(10,7);Triangle tri(10,5);//多态shape = &rec;shape->area(); //Rectangle::area()shape = &tri;shape->area(); //Triangle::area()return 0; }