现在的位置: 首页 > 综合 > 正文

C++覆盖和隐藏

2013年02月23日 ⁄ 综合 ⁄ 共 697字 ⁄ 字号 评论关闭

#include<iostream>
using namespace std;
class Base
{
public:
 virtual void xfn(int i)
 {
  cout<<"Base::xfn(int i)"<<endl;
 }

 void yfn(float f)
 {
  cout<<"Base::yfn(float f)"<<endl;
 }

 void zfn()
 {
  cout<<"Base::zfn()"<<endl;
 }
};
class Derived:public Base
{
public:
 void xfn(int i)
 {
  cout<<"Derived::xfn(int i)"<<endl;
 }
 void yfn(int c)
 {
  cout<<"Derived::yfn(int n)"<<endl;
 }
 void zfn()
 {
  cout<<"Derived::zfn()"<<endl;
 }
};
void main()
{
 Derived d;
 Base *pB=&d;
 Derived *pD=&d;
 
 pB->xfn (5);
 pD->xfn(5);
 
 pB->yfn(3.14f);
 pD->yfn(3.14f);
 
 pB->zfn();
 pD->zfn();
}

函数的覆盖是发生在派生类和基类之间,两个函数必须完全相同,并且都是虚函数。那么不属于这种情况的就是隐藏了

运行结果:

Derived::xfn(int i)
Derived::xfn(int i)
Base::yfn(float f)
Derived::yfn(int n)
Base::zfn()
Derived::zfn()
Press any key to continue

抱歉!评论已关闭.