函数重载
必须在同一个类中进行
子类无法重载父类的函数,父类同名函数将被名称覆盖
重载是在编译期间根据参数类型和个数决定函数调用
函数重写
必须发生于父类与子类之间
并且父类与子类中的函数必须有完全相同的原型
使用virtual声明之后能够产生多态(如果不使用virtual,那叫重定义)
多态是在运行期间根据具体对象的类型决定函数调用
即 重写分为两分类:虚函数重写发生多态,非虚函数重写发生重定义
#include <iostream>
using namespace std;
class Parent{
public:
void print(){
cout << "this is parent Print()--" << endl;
}
void print(int i,int j){
cout << "this is parent print(int i,int j)--" << endl;
}
virtual void func(){
cout << "this is parent func()--" << endl;
}
virtual void func(int i){
cout << "this is parent func(int i)----" << endl;
}
virtual void func(int i, int j){
cout << "this is parent func(int i,int j)---" << endl;
}
virtual void func(int i, int j, int mm ,int m ){
cout << "this is Parent func(int i,int j,int mm int m)---" << endl;
}
protected:
private:
};
class Child :public Parent{
public:
void print(){
cout << "this is child Print(int i,int j)--" << endl;
}
void print(int i){
cout << "this is child Print(int i)--" << endl;
}
virtual void func(int i, int j){
cout << "this is child func(int i,int j)---" << endl;
}
virtual void func(int i,int j,int m){
cout << "this is child func(int i,int j,int m)---" << endl;
}
};
int main()
{
Child c;
c.print(1);
c.Parent::print(1, 2);
//c.func(); //子类无法重载父类的函数
c.Parent::func(); //只能通过作用域调用
c.func(2, 3);
c.print();
//c.func(1, 2, 3, 4);error
system("pause");
return 0;
}