// test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <cstdlib>
#include <new>
#include <iostream>
using namespace std;
class Base{
public:
int f(){
cout<<"int f() Base"<<endl;
return 0;
}
void f(int){
cout<<"void f() Derived1"<<endl;
}
};
class Derived1:public Base{
public:
void f(){
cout<<"void f() Derived1"<<endl;
}
};
class Derived2:public Base{
public:
void f(int){
cout<<"void f(int) Derived2"<<endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Derived1 d1;
Derived2 d2;
Base b;
b.f();
d1.f();
d2.f();//错误,定义void f(int),使得Base::f不可见。
d2.f(1);
return 0;
}
在派生类中定义与基类同名的函数时,不管参数和返回值是不是相同的,只要名字相同,则基类中的函数被重写。所有与该函数同名的函数都被隐藏。

本文通过C++示例代码介绍了派生类如何通过定义与基类同名的函数来实现函数的重写与隐藏现象。无论是参数类型还是返回值相同与否,只要函数名一致,基类中的函数即被重写,而同名的不同函数则会被隐藏。
440

被折叠的 条评论
为什么被折叠?



