C++函数重定义、重载、重写
来源:互联网 发布:玻璃排版软件 编辑:程序博客网 时间:2024/05/17 02:37
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此函数名,而不会遮蔽它在基类中定义的任何版本。即重载写在基类、子类都能得到执行。
- 函数重载重写重定义
- C++(多态实现原理)函数重写,重载,重定义
- [C++]函数的重载、重写和重定义的区别
- C++函数重定义、重载、重写
- C++函数重定义、重载、重写
- C++函数重定义、重载、重写
- C++函数重定义、重载、重写
- 函数重载/重写/重定义(覆盖)
- C++函数重定义、重载、重写
- C++函数重定义、重载、重写
- C++函数重定义、重载、重写
- C++函数重载、重定义、重写
- C++函数重定义、重载、重写
- C++函数重定义、重载、重写
- C++函数重定义、重载、重写
- C++函数重定义、重载、重写
- C++函数重定义、重载、重写
- C++函数重定义、重载、重写
- vi的基本操作
- 2008年6月大学英语四级考试真题答案与精解 (试卷A)
- 对自己好点
- 蓝海战略
- 常见字母读法
- C++函数重定义、重载、重写
- 道cpu、道指令、道编程基本原理17
- 查找指定类型的驱动器
- Libxml 指南
- office打开提示需要安装的解决
- 热插拔的设备的拔出与插入的响应
- 地中海上空的木星
- 开发人员的人生方向
- c++资源大全