重载,覆盖,隐藏

关于重载,覆盖,隐藏的文章很多,有的也写的很好,我这就当重新温习下

1、在c++中,重载是一个类内部实现相同机制的成员函数,特征主要有:

1、在一个类中

2、重载的方法名称相同

3、参数不同(参数的类型,参数的个数),返回值无法确定其是否重载

4、virtual函数可有可无

一个经典的例子:

#include <stdio.h>
#include <iostream>


using namespace std;


class algorithm
{
public:
    void add(int a, int b); 
    void add(int a, int b, int c); 
    void add(int a, double b); 
    void add(double a, int b); 
    void add(double a, double b); 
private:
    
};


void algorithm::add(int a, int b)
{
    printf("int a+b :%d\r\n", a+b);
}


void algorithm::add(int a, int b, int c)
{
    printf("int a+b+c: %d\r\n", a+b+c);
}
void algorithm::add(int a, double b)
{
    printf("int a + double b : %lf\r\n", a+b);
}


void algorithm::add(double a, int b)  
{
    printf("double a + int b : %lf\r\n", a+b);
}
void algorithm::add(double a, double b)
{
    printf("doubel a+double b :%lf\r\n", a+b);
}


int main()
{
    algorithm c;
    c.add(1, 2); 
    c.add(1, 2, 3); 
    c.add(1.1, 2); 
    c.add(1, 2.2);
    c.add(1.1, 2.2);
    return 0;
}




例子中对add进行了重载,既有参数类型不同的重载,也有参数个数不同的重载,还有参数顺序不同的重载。


2、覆盖

覆盖就是面向对象中的多态,通过多态针对同一行为,可以表现出不同的操作,是子类覆盖基类的方法。主要体现在:

1、是子类和父类的关系(派生类和基类)

2、函数名相同,并且参数相同

3、基类函数中要有virtual修饰

例子:

#include <iostream>
#include <stdio.h>


class animal
{
public:
    virtual void cry();


};


void animal::cry()
{
    printf("animal cry \r\n");
}


class dog :public animal
{
public:
   void  cry();
};


void dog::cry()
{
    printf("dog cry \r\n");
}


int main()
{
    dog d;
    animal *a = &d; 
    a->cry();
    return 0;
}


子类覆盖父类的方法

输出:dog cry

3、隐藏

隐藏是派生类屏蔽基类的同名函数,主要体现在:

1、如果派生类的函数和基类的函数同名,但是参数不同,这样不论基类函数是否有virtual,基类都将被隐藏

2、如果派生类的函数和基类的函数同名,并且参数也相同,但是基类中没有virtual修饰,基类也将被隐藏

例子:

#include <iostream>


using namespace std;


class animal
{
public :
    virtual void eat(double a); 
    virtual void eat(double a, double b); 
};


void animal::eat(double a)
{
    cout<<"eat double a"<<endl;
}
void animal::eat(double a, double b)
{
    cout<<"eat double a, double b"<<endl;
}


class dog : public animal
{
public :
    void eat(int a); 
};


void dog::eat(int a)
{
    cout<<"eat int a"<<endl;
}


int main()
{
    dog d;
    d.eat(1);
    d.eat(1.1,2.2);
    return 0;
}



输出;

当只有d.eat(1),准确的输出该值,当加上d.eat(1.1,2.2),编译出现:


显示没有匹配函数,说明基类的函数隐藏了。


关于这方面的内容先到这。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值