C++中的覆盖、重载与隐藏

10 篇文章 0 订阅

    c++中类本身之间的函数关系与基类和子类之间的函数关系有:覆盖、重载与隐藏。

1>覆盖:C++中在基类用virtual定义的函数在子类中重新定义,此时称为覆盖,即子类对父类函数的覆盖。

2>重载:同一个类中定义了多个同名但其形参不同的函数,这些同名函数之间为重载。

3>隐藏:函数的隐藏有两种情况。第一,如果派生类的函数与基类的函数同名,但是参数不同。此时,不论有无virtual 关键字,基类的函数将被隐藏;第二,如果派生类的函数与基类的函数同名,并且参数也相同,但是基类函数没有virtual
关键字。
此时,基类的函数被隐藏。

#include<iostream>  
using namespace std;  
class Base  
{  
public:  
    virtual void f(float x)  
    {  
        cout<<"Base::f(float)"<< x <<endl;  
    }  
    void g(float x)  
    {  
        cout<<"Base::g(float)"<< x <<endl;  
    }  
    void h(float x)  
    {  
        cout<<"Base::h(float)"<< x <<endl;  
    }  
};  
class Derived : public Base  
{  
public:  
    virtual void f(float x)  
    {  
        cout<<"Derived::f(float)"<< x <<endl;   //覆盖  
    }  
    void g(int x)  
    {  
        cout<<"Derived::g(int)"<< x <<endl;     //隐藏  
    }  
    void h(float x)  
    {  
        cout<<"Derived::h(float)"<< 2*x <<endl;   //隐藏  
    }  
<pre name="code" class="cpp" style="color: rgb(51, 51, 51); line-height: 26px;">    void h(int x)  
    {  
        cout<<"Derived::h(int)"<< x <<endl;   //重载 
    } 
}; int main() { Derived d; Base *pb = &d; Derived *pd = &d; pb->f(3.14f); // Derived::f(float) 3.14 pd->f(3.14f); // Derived::f(float) 3.14 pb->g(3.14f); // Base::g(float) 3.14 pd->g(3.14f); // Derived::g(int) 3 pb->h(3.14f); // Base::h(float) 3.14 pd->h(3.14f); // Derived::h(float) 6.28

 
<pre name="code" class="cpp" style="color: rgb(51, 51, 51); line-height: 26px;">    pd->h(3);   // Derived::h(int) 3
return 0; }
 
上述代码中: 

(1)函数Derived::f(float)覆盖了Base::f(float)。
(2)函数Derived::g(int)隐藏了Base::g(float)。
(3)函数Derived::h(float)隐藏了Base::h(float)。

(4)函数Derinved::h(int)重载了Derived::h(float),反之亦然,重载的函数之间是相互的。

    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值