C++多态补充内容

xiaoxiao2021-02-28  23

1.虚析构函数

virtual~class()

1.如果只有析构函数时,在析构基类指针时,只有基类的函数被析构,子类函数不会被析构,因此可能内存泄漏

2.在基类定义为虚析构函数时,所有派生类均都定义为虚析构函数

3.构造对象后直接调用类本身的析构函数,进行回收

4.构造函数不能被定义为虚函数

2.抽象类

1.含有纯虚函数的类

virtual fun_name()=0;//只有声明,没有定义

2.只能为派生类的基类

3.不能定义对象,只能定义指针

class Ishape { public: //多态性实现需要虚方法 virtual double get_Area() = 0;//纯虚函数 virtual string get_Name() = 0;//纯虚函数 };

4.子类可以去重写基类的虚函数 实现多态性

class CRect :public Ishape { public: CRect(double length, double width) { this->m_length = length, this->m_width = width;} CRect(){}; virtual double get_Area();//重写基类函数 体现了多态性 晚联编 virtual string get_Name();//重写基类函数 体现了多态性 早联编 private: double m_length; double m_width; }; double CRect::get_Area() { return m_length*m_width; } string CRect::get_Name() { return "Rectangle";

3.运算符重载(opreator)

1.前置自加操作

//运算符重载(前置自加) //先自加后赋值 #include<iostream> class number { private: int i; public: number() { i = 1; } void set_num(int n) { n = i; } void operator++() { ++i; } /*(number operator++() { num n1; }*/ void get_num() { std::cout << i << std::endl; } }; #include<iostream> #include"head.h" void main() { number n1; n1.get_num(); n1.operator++(); n1.get_num(); ++n1;//等于n1.operator++(); n1.get_num(); //number n2 = n1.operator++(); system("pause"); }

注:++n1;//重载++运算符,直接实现对对象进行操作

n1.operator++()

2.后置自加操作

#include<iostream> #include"head.h" void main() { number n1; n1.get_num(); n1++;//等于n1.operator++(); n1.get_num(); system("pause"); } //运算符重载(后置自加) //先赋值再自加 #include<iostream> class number { private: int i; public: number() { i = 2; } number(int num) { i = num; } ~number() {} void set_num(int n) { n = i; } number operator++(int ) { number n1(this->i); this->i++; return n1; } void get_num() { std::cout << i << std::endl; } }; #include<iostream> #include"head.h" void main() { number n1; n1.get_num(); n1++;//等于n1.operator++(); n1.get_num(); system("pause"); }

注:前置自加和后置自加的判断方法(后置自加含参数)

number operator++(int )//后置自加

number operator++//前置自加参考资料:http://www.runoob.com/cplusplus/cpp-overloading.html

转载请注明原文地址: https://www.6miu.com/read-2633125.html

最新回复(0)