C++多态补充内容

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





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值