您的位置:首页 > 其它

重写 重载 隐藏

2016-04-10 11:30 302 查看
C++中有很多概念,很容易混淆,下面主要来说一下重载,重写和隐藏的区别:

重载:overload  --函数名一样,函数的参数不同(包括参数的个数,参数的类型),返回值没有要求:

重写:override --函数名称,参数,返回值一样(返回值仅限父类和子类的时候不一样);

隐藏:hide--重载的函数放在子类和父类中就会形成隐藏:

#include <iostream>
using namespace std;
void aa(int a ) //函数的重载,函数名称相同,函数参数不一样,根据参数的个数来调用函数;
{
cout<<"aa"<<endl;
}

void aa(int a,int b)
{
cout<<a<<b<<endl;
}

class father
{
public:
void show()
{
cout<<"this is the father"<<endl;
}
void cc()
{
cout<<"this is the father cc"<<endl;
}
};

class son :public father
{
public:
void show() //重写父类的show函数;名称参数一样,功能不一样;
{
cout<<"this is the son show"<<endl;
}

void cc(int a ,int b) //隐藏不能根据函数的参数来调用函数,只能用对象或者类名+::作用域来调用;
{ //把father中的cc隐藏了;
cout<<"this is the son cc"<<endl;
}

};
int main()
{
son s;
s.father::cc(); //类名+ ::来调用隐藏的函数;
s.cc(100,200);
s.show();
s.father::show();
system("pause");
return 0;
}


重载只是一种语言特性,与多态无关,因为它是在编译期间就进行了函数的绑定,也就是静态绑定,属于早绑定!早绑定与静态绑定与多态和面向对象无关!


void fun(int a);

void fun(int a, char *b);

经过编译后,在编译期间可能处理为:i_fun()和char_fun(),这样的标示和绑定!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: