重载:在同一作用域内定义多个同名函数,但要求这些函数具有参数的类型或个数不相同,返回值类型不影响。
重定义:若是在同一作用域内,定义了同名,参数类型和个数也相同的函数,编译时会出现重定义错误。但是若是派生类继承了父类,重新定义了该函数不会报错。而且,不管该函数参数类型是否一致,都会被派生类重定义。
重写:针对多态性,利用同一接口实现不同的实例。若是不声明虚函数,在派生类会重定义基类同名函数。这样便无法实现用基类指针调用派生类函数的目的。
注意:重载一定发生在同一作用域内;重定义发生在基类和派生类中,只要函数名一致就会重定义;重写需要函数名,参数类型一致,基类定义虚函数。测试重载和重定义,重写联合使用的情况。
(1)在基类中重载,在派生类中重定义,派生类对象只能调用派生类中定义了的函数类型,而无法调用从基类继承过来的同名重载函数类型;基类自然是可以调用自身的重载函数。
(2)在基类中不重载,在派生类中重定义+重载,派生类可以调用自己的任何重载函数。
(3)在重写的派生类中重载是不允许的,但是可以在基类中重载虚函数。
#include<bits/stdc++.h>
using namespace std;
void OverLoadTest()
{
cout<<"测试重载"<<endl;
}
int OverLoadTest(int a)
{
cout<<"测试重载 a= "<<a<<endl;
return a;
}
class TestReDefineBase{
private:
int a;
public:
TestReDefineBase(int b):a(b){
}
~TestReDefineBase(){
}
void TestFuc()
{
cout<<"我是测试重定义的基类"<<endl;
}
void TestFuc(int a)
{
cout<<"我是测试重定义的基类 a="<<a<<endl;
}
};
class TestReDefineDerive:public TestReDefineBase{
private:
int b;
public:
TestReDefineDerive(int d,int e):TestReDefineBase(d),b(e){
}
~TestReDefineDerive(){
}
//重定义
void TestFuc()
{
cout<<"我是测试重定义的派生类"<<endl;
}
//重定义了TestFuc,在类内作用域内重载了TestFun
// int TestFuc(int c)
// {
// cout<<"我是测试重定义的派生类 c= "<<c<<endl;
// return c;
// }
};
class TestReWriteBase{
private:
int a;
public:
TestReWriteBase(int b):a(b){
}
~TestReWriteBase(){
}
virtual void TestFuc()
{
cout<<"我是测试重写的基类"<<endl;
}
virtual int TestFuc(int a)
{
cout<<"我是基类重载的函数"<<endl;
return a;
}
};
class TestReWriteDerive:public TestReWriteBase{
private:
int b;
public:
TestReWriteDerive(int d,int e):TestReWriteBase(d),b(e){
}
~TestReWriteDerive(){
}
//重写
void TestFuc()
{
cout<<"我是测试重写的派生类"<<endl;
}
// //重载 错误的
// void TestFuc(int c)
// {
// cout<<"我是测试重写的派生类 c="<<c<<endl;
//
// }
//重定义了TestFuc,在类内作用域内重载了TestFun
int TestFuc(int c)
{
cout<<"我是测试重写的派生类 c= "<<c<<endl;
return c;
}
};
int main()
{
//测试重载
int a=10;
OverLoadTest();
OverLoadTest(a);
//测试重定义
TestReDefineBase t1(10);
TestReDefineDerive t2(10,20);
t1.TestFuc();
t1.TestFuc(100);
t2.TestFuc();
//测试重写
TestReWriteBase *p;
TestReWriteBase c1(30);
TestReWriteDerive c2(30,40);
p=&c1;
p->TestFuc();
p=&c2;
p->TestFuc();
p->TestFuc(10);
return 0;
}