面对对象的程序设计:
对象构成:(解释:面对对象更接近人的思维)
{
①属性
②行为
};
类:(解释:具有相同属性和行为的对象)
(1)抽象:简单来说就是定义一个类的过程。
(2)封装:(解释:定义类的时候,用大括号将其当作为一个整体)
最简单的结构 :
class student {
//访问属性;
成员变量;
成员函数;
};
//类定义时:可将个别属性(成员变量)和功能(成员函数)声明为private(“私有”)访问属性。//
//目的:设定除了类的成员函数,其他函数是不能直接访问这些被声明为private访问属性的成员。//
(3)继承(解释:代码可以重复利用):就是所谓的“子类”,比如:已经建立一个A类,在建立一个B类,只需在A的基础上添加一些行为和属性。
(4)多态:不同的对象接受同一个命令,通过各自不同的动作达到实现目标的现象。
#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()
{
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape{
public:
Rectangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
class Triangle: public Shape{
public:
Triangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
// 程序的主函数
int main( )
{
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
// 存储矩形的地址
shape = &rec;
// 调用矩形的求面积函数 area
shape->area();
// 存储三角形的地址
shape = &tri;
// 调用三角形的求面积函数 area
shape->area();
return 0;
}
输出:
Rectangle class area :
Triangle class area :