学习网站:C语言网.
C语言基础:C语言基础.
笔记及源码gitee地址:C++基础笔记及源码.
编译器:Red Panda Dev-C++.
1.多态性
// 1.多态:在面向对象程序设计中,指同样的方法被不同对象执行时会有不同的执行效果; // 2.多态实现:编译时多态、运行时多态; // 2.1 编译时多态:编译的时候确定具体操作过程; // 2.2 运行时多态:在程序运行过程中确定的操作过程; // 3.联编:一个计算机程序自身彼此关联的过程,在这个联编过程中,需要确定程序中的操作调用与执行该操作的代码段之间的映射关系; // 3.1 静态联编:在程序编译连接阶段进行,称为早期联编,这种联编在程序开始运行前完成;在程序编译阶段进行的这种联编在编译时解决了程序的操作调用与执行该操作代码间的关系; // 3.2 动态联编:编译程序在编译阶段不能确切确定将要调用的函数,只有在程序执行时才能确定要调用的函数;
#include2.虚函数using namespace std; #define PI 3.1415926 class Point { private: int x,y; public: Point(int x = 0,int y = 0){ this->x = x; this->y = y; } double area(){ return 0.0; } }; class Circle:public Point { private: int r; public: Circle(int x,int y,int R):Point(x,y){ r = R; } double area(){ return PI*r*r; } }; int main(){ Point A(10,10); cout << "A.area:" << A.area() << endl; // 按Point类area方法输出; Circle B(10,10,20); cout << "B.area:" << B.area() << endl; // 按派生类Circle的area方法输出; // 以下均采用静态联编; Point *p; // Point类型指针p指向的Circle类对象的area方法; p = &B; cout << "p->area:" << p->area() << endl; Point &pp = B; // 把Circle类型的对象赋给Point类型的引用; cout << "pp.area:" << pp.area() << endl; return 0; }
// 1.虚函数的出现,允许函数在调用时与函数体的联系在运行时才建立,即动态联编; #include3.虚析构函数using namespace std; #define PI 3.1415926 class Point { private: int x,y; public: Point(int x = 0,int y = 0){ this->x = x; this->y = y; } virtual double area(){ return 0.0; } }; class Circle:public Point { private: int r; public: Circle(int x,int y,int R):Point(x,y){ r = R; } double area(){ return PI*r*r; } }; int main(){ Point A(10,10); cout << "A.area:" << A.area() << endl; Circle B(10,10,20); cout << "B.area:" << B.area() << endl; Point *p; p = &B; cout << "p->area:" << p->area() << endl; Point &pp = B; cout << "pp.area:" << pp.area() << endl; return 0; } // Tips: // a.虚函数不能是静态成员函数,或友元函数,因为它们不属于某个对象; // b.内联函数不能在运行中动态确定其位置,即使虚函数在类的内部定义,编译时,仍将看作非内联; // c.构造函数不能是虚函数,析构函数可以是虚函数,且通常声明为虚函数;
// 1.虚析构函数:在用基类的指针指向派生类的对象在释放时,可以根据实际所指向的对象类型动态联编调用子类的析构函数,实现正确的对象内存释放; #include4.纯虚函数与抽象类using namespace std; class Point { private: int x,y; int *str; public: Point(int x = 0,int y = 0){ this->x = x; this->y = y; str = new int[100]; } // 基类析构函数声明为virtual时,会先调用释放派生类的空间, // 再释放基类的内存空间,不会造成内存残留; virtual ~Point(){ delete []str; cout << "Called Point's Destructor and Deleted str!" << endl; } }; class Circle:public Point { private: int r; int *str; public: Circle(int x,int y,int R):Point(x,y){ r = R; str = new int[100]; } ~Circle(){ delete []str; cout << "Called Circle's Destructor and Deleted str!" << endl; } }; int main(){ Point *p; p = new Circle(10,10,20); delete p; return 0; }
// 1.纯虚函数:没有函数体的虚函数,定义:virtual 返回值 函数名 (形参)=0; // 2.抽象类:包含纯虚函数的类,一个抽象类至少有一个纯虚函数; // 3.抽象类的特点: // 3.1 抽象类无法实例出一个对象,只能作为基类让派生类完善其中的纯虚函数,然后再实例化使用; // 3.2 抽象类的派生类依然可以不完善基类中的纯虚函数,继续作为抽象类被派生,直到给出所有纯虚函数的定义,则完成一个具体类,才可以实例化对象; // 3.3 抽象类因为抽象,无法具体化,因此不能作为参数类型,返回值,强转类型; // 3.4 抽象类可以定义一个指针,引用类型,指向其派生类,来实现多态特性;



