C++的多态性

C++的多态性主要是重载虚函数。(也就是静态多态性和动态多态性)

一:
先是重载,分为函数重载和运算符重载。

函 数 重 载 : \color{red}{函数重载:} 虽然函数名相同,但是函数内容不同,靠参数不同来区分。
例子:
对 f() 进行重载:

#include<iostream>
using namespace std;

int f(int x,int y)  //进行加法运算
{
    return x+y;
}

float f(float x,float y)  //进行乘法运算
{
    return x*y;
}

int main()
{
    int a=1;
    int b=2;
    float c=1;
    float d=2;
    cout<<f(a,b)<<endl;
    cout<<f(c,d)<<endl;
    return 0;  
}

在这里插入图片描述
运 算 符 重 载 : \color{red}{运算符重载:} (一般用于类,自定义输出格式,自定义加法运算等等)
例:

#include<iostream>
using namespace std;

class person
{
    string name;
    int age;
    public:
        person(){name="MJ";age=18;}
        friend ostream & operator<<(ostream & out,const person &A);

};

ostream & operator <<(ostream & out,const person&A) 
{
    out<<A.name<<endl;
    out<<A.age<<endl;
    return out;
}

int main()
{
    person A;
    cout<<A;
    return 0;  
}

输出重载必须为友元函数,因为左边的运算对象是cout流而不是对象本身

说 明 : o s t r e a m 的 引 用 为 返 回 值 类 型 , 然 后 函 数 名 是 o p e r a t o r < < , 这 其 实 就 是 和 默 认 输 出 函 数 的 重 载 \color{red}{说明:ostream的引用为返回值类型,然后函数名是operator<<,这其实就是和默认输出函数的重载} ostreamoperator<<

二:虚函数
简单地说就是使用基类派生类中通过virtual关键字使得同名同参的函数共存
访问时可以借助基类指针指向访问
例:

#include<iostream>
using namespace std;

class Base	//基类
{
     public:
        int a;	//基类中的a
	    Base(int y){a=y;}
	    virtual void Print(){cout<<"基类:"<<a<<endl;}
	    
};

class Derive: public Base  //派生类
{
     public:
	   int a;   //派生类中的同名a
       Derive(int x,int y):Base(y){a=x;}
	   void Print(){cout<<"派生类:"<<a<<endl;}
};

int main()
{
    Derive A(1,10);
    Base B(10);
    Base *p;
    p=&A;
    p->Print();
    p=&B;
    p->Print();
    return 0;  
}

在这里插入图片描述
虽然Derive 类中有两个Print函数,而且参数也一样,但是仍然可借助虚函数共存

在虚函数的基础上,再介绍纯虚函数:
在基类中没有虚函数的具体定义,然后在各个派生类中再定义

例:
在这里插入图片描述

class Point    //基类:声明纯虚函数
{     public:
         virtual void Draw ()=0;   //基类:
};
void Line::Draw()    //派生类:重新定义Draw()
{ 
     cout<<"Line::Draw is called.\n";   
}
void Circle::Draw()    //派生类:重新定义
{
	cout<<“Circle::Draw is called.\n";   
}

由纯虚函数又衍生出了抽象类~(体现了何为面向对象)
基类主要用于集合各个派生类
在这里插入图片描述

class Shape 	//抽象基类:Shape
{       
    public:
         //声明纯虚函数
	   virtual double area() const=0;  
};
double Triangle::area() const    //派生类:重定义area()函数
{     
    return 0.5*base*hight;  
}
double Rectangle::area() const     //派生类:重定义area()函数
{    
    return length*width;   
}
double Circle::area() const {    //派生类:重定义area()函数
{    
    return PI*radius*radius;   
}

Ps:const 表示常成员函数,不对数据进行修改

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值