C++函数重定义、重载、重写

来源:互联网 发布:Matlab数据精度 编辑:程序博客网 时间:2024/05/16 17:36

1. 重写 (override):

      父类与子类之间的多态性。子类重新定义父类中有相同名称和参数的虚函数。

1) 被重写的函数不能是 static 的。必须是 virtual 的,或者是 override 的 ( 即函数在最原始的基类中被声明为virtual , c++ 中没有 override) 。

2) 重写函数必须有相同的类型,名称和参数列表

3) 重写函数的访问修饰符可以不同。尽管 virtual 是 private 的,派生类中重写改写为 public,protected 也是可以的 ( 这点与 C# 完全不同 )

2. 重载 (overload):

      指函数名相同,但是它的参数表列个数或顺序,类型不同。但是不能靠返回类型来判断。

 

3. 重定义 (redefining):

      子类重新定义父类中有相同名称的非虚函数 ( 参数列表可以不同 ) 。

 

class Base {

   private:

      virtual void display() { cout<<"Base display()"<<endl; }

      void say(){

         cout<<"Base say()"<<endl;

      }

   public:

      void exec(){

         display();

         say();

      }

      void f1(string a)  { cout<<"Base f1(string)"<<endl; }

      void f1(int a) { cout<<"Base f1(int)"<<endl; }   //overload

};

 

class DeriveA:public Base{

   public:

      void display() { cout<<"DeriveA display()"<<endl; }   //override

      void f1(int a,int b) { cout<<"DeriveA f1(int,int)"<<endl; }   //redefining

   public:

      void say() { cout<<"DeriveA say()"<<endl; }   //redefining

};

 

class DeriveB:public Base

{

   public:

      void f1(int a) { cout<<"DeriveB f1(int)"<<endl; }  //redefining

};

 

int main(){

   DeriveA a;

   Base *b=&a;

   b->exec();        //display():version of DeriveA called(polymorphism)                          

                  //say():version of Base called(allways )

   a.exec();        //same result as last statment

   a.say();

   //a.f1(1);         //error:no matching function, hidden !!

   DeriveB c;

   c.f1(1);         //version of DeriveB called

}

注意:在 C++ 中若基类中有一个函数名被重载,在子类中重定义该函数,则基类的所有 版本将被隐藏——即子类只能用子类定义的,基类的不再可用。——名字隐藏特性。

      Java 的基类中定义多个被重载的函数,在子类中可 override/redefining 此函数名,而不会遮蔽它在基类中定义的任何版本。即重载写在基类、子类都能得到执行。

原创粉丝点击