您的位置:首页 > 编程语言 > C语言/C++

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

2015-07-28 15:21 387 查看
    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),反之亦然,重载的函数之间是相互的。

    
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ vc