Overload and override in c++

来源:互联网 发布:手机网络枪战游戏排行 编辑:程序博客网 时间:2024/06/02 05:08
Overload

C++ allow you to specify more than one definitions for a function name or an operator in the same scope,which is called function overloading and operator overloading respectively.

Consider the following example:
example one:

#include<iostream>using namespace std;class A{    int x;public:    void print(){std::cout<<"print:1"<<endl;}    void print(int a){std::cout<<"print int:"<<a<<endl;}    void print(double a){std::cout<<"print double:"<<a<<endl;}        //conflict with void print(double)    //double print(double a){return a;}};int main(int argc, char *argv[]){    A* a = new A;    a->print();    a->print(2);    a->print(300.00);    /*    A a;    a.print();    a.print(2);    a.print(300.243);    */    return 0;}

There are three elements in function overload:

  • in the same scope
  • the same function name
  • different arguments

example two
contents about operator overloading will be fullfilled int he future.

Override

C++ allow you to override a virtual method of the base class, which has a key word “virtual” in front.

Consider the following example:

#include<iostream>using namespace std;class A{    int x;public:    virtual void func(){}};class B:A{    int y;public:    void func()  {cout<<"overriding"<<endl;}};int main(int argc, char*argv[]){    B* b = new B();    b->func();    return 0;}
原创粉丝点击