原文:http://hi.baidu.com/pweiwen/blog/item/ac4bbf161123c81e972b435f.html
1、C++函数重写
1)被重写的函数不能是static的。必须是virtual的,或者是override的(即函数在最原始的基类中被声明为virtual,c++中没有override)。
2)重写函数必须有相同的类型,名称和参数列表
3)重写函数的访问修饰符可以不同。尽管virtual是private的,派生类中重写改写为public,protected也是可以的(这点与C#完全不同)
2、C++函数重载
1)直观的理解,重载就是一个名称相同的函数有不同版本(参数列表不同:参数类型,顺序)。
2)构成重载函数集的函数必须在同一个域。例如,试图在基类和派生类中的同名函数集中构成一个重载集,将引发错误(函数调用时,编译错误),事实上,派生类中的新函数“版本”隐藏了基类中定义的函数(隐藏在C++很少提及,但存在)
下面是一段很变态的程序(为了说明问题),在实际应用中应该避免出现。
#include <iostream.h>
#include <string.h>
class Base
{
private:
virtual void display(){
cout<<"base display"<<endl;
}
void say(){
cout<<"base say!"<<endl;
}
public:
void exec(){
display();
say();
}
void f1(int a,char b){
cout<<a<<b<<endl;
}
void f1(int b,int a){
cout<<"b:"<<b<<a<<endl;
}
};
class DeriveA:public Base
{
public:
void display(){
cout<<"protected DeriveA fun"<<endl;
}
void f1(int a,int b,int c){
cout<<a<<b<<c<<endl;
}
protected:
void say(){
cout<<"DeriveA say!"<<endl;
}
};
int main(){
DeriveA a;
Base *b=&a;
b->exec();
a.exec();
a.f1(1,2); //error:no matching function
}