C++基类与子类的重名函数调用情况分析

编译器只通过函数名称、函数参数个数与类型来判断函数是否重载,不考虑返回值类型,故,下面本文例子返回值一律使用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 (;;);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值