您的位置:首页 > 编程语言 > C语言/C++

Overload and override in c++

2017-05-27 15:52 459 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++