编译器只通过函数名称、函数参数个数与类型来判断函数是否重载,不考虑返回值类型,故,下面本文例子返回值一律使用void
#include <iostream>
using namespace std;
//基类
class base
{
public:
virtual ~base() {}
void fun1(int a) {
std::cout << "base::fun1(int)---" << a << endl;
}
void fun2(float a) {
std::cout << "base::fun2(float)---" << a << endl;
}
virtual void fun3(int a) {
std::cout << "base::fun3(int)---" << a << endl;
}
virtual void fun4(float a){
std::cout << "base::fun4(float)---" << a << endl;
}
};
//子类
class sub : public base
{
public:
void fun1(int a) {
std::cout << "sub::fun1(int)---" << a << endl;
}
void fun2(int a) {
std::cout << "sub::fun2(int)---" << a << endl;
}
void fun2(string a) {
std::cout << "sub::fun2(string)---" << a << endl;
}
virtual void fun3(int a) {
std::cout << "sub::fun3(int)---" << a << endl;
}
virtual void fun4(int a) {
std::cout << "sub::fun4(int)---" << a << endl;
}
};
int main()
{
base* p = new sub();
sub s;
//下面注释表示实际调用的函数,ERROR表示编译器报错
p->fun1(1); //base::fun1(int)
p->base::fun1(1); //base::fun1(int)
// p->sub::fun1(1); //ERROR
s.fun1(1); //sub::fun1(int),子类覆盖基类的fun1
s.base::fun1(1); //base::fun1(int)
std::cout << "-------------------------------" << endl;
p->fun2(1); //base::fun2(float),1隐式转换为float
p->fun2(0.5); //base::fun2(float)
p->base::fun2(1); //base::fun2(float),1隐式转换为float
p->base::fun2(0.5); //base::fun2(float)
s.fun2(1); //sub::fun2(int)
s.fun2(0.5); //sub::fun2(int),0.5隐式转换为int
s.base::fun2(1); //base::fun2(float),1隐式转换为float
s.base::fun2(0.5); //base::fun2(float)
s.fun2("asd"); //sub::fun2(string)
//p->fun2("asd"); //ERROR
std::cout << "-------------------------------" << endl;
//子类重写基类的fun3
p->fun3(1); //sub::fun3(int)
p->base::fun3(1); //base::fun3(int)
// p->sub::fun3(1); //ERROR
s.fun3(1); //sub::fun3(int)
s.base::fun3(1); //base::fun3(int)
std::cout << "-------------------------------" << endl;
//因为参数不同,所以子类并没有重写基类的fun4
p->fun4(1); //base::fun4(float),1隐式转换为float
p->fun4(0.5); //base::fun4(float)
p->base::fun4(1); //base::fun4(float),1隐式转换为float
p->base::fun4(0.5); //base::fun4(float)
s.fun4(1); //sub::fun4(int)
s.fun4(0.5); //sub::fun4(int),0.5隐式转换为int
s.base::fun4(1); //base::fun4(float),1隐式转换为float
s.base::fun4(0.5); //base::fun4(float)
std::cout << "-------------------------------" << endl;
for (;;);
}