C++ 虚函数覆盖、重载

CBase类处于作用域的外层,派生类的方法对于其将是不可见的,即隐藏的。而在派生类中,如果有重载函数时,基类函数将会被隐藏,否则基类函数就不被隐藏。 

#include
using namespace std;

//基类
class CBase
{
public:
	CBase();
	~CBase();
	virtual void Walk() { cout << "CBase:Walk" << endl; }
	virtual void Jump() { cout << "CBase:Jump" << endl; }

	void Run(int speed) { cout << "CBase:Run:" << "Speed=" << speed << endl; }
	
};

//派生
class CDerivedA : public CBase
{
public:
	CDerivedA();
	~CDerivedA();
	void Walk() { cout << "CDerivedA:Walk" << endl; }
	void Jump() { cout << "CDerivedA:Jump" << endl; }
	void Run(int speed) { cout << "CDerivedA:Run" << "Speed=" << speed << endl; }
	void Run(int speed, int direction) { cout << "CDerivedA:Run" << "Speed=" << speed << ";Direction=" << direction << endl; }
};

CBase::CBase()
{

}
CBase::~CBase()
{

}
CDerivedA::CDerivedA()
{

}
CDerivedA::~CDerivedA()
{

}

int main() 
{

	CBase *pTmp1 = new CDerivedA;
	pTmp1->Walk();
	pTmp1->Jump();
	pTmp1->Run(20);

	CDerivedA *pTmp2 = (CDerivedA*)pTmp1;
	pTmp2->Run(20, 3);//合法的
	//pTmp1->Run(20,3);//不合法
}

C++ 虚函数覆盖、重载_第1张图片

说明:

1. CDerived和CBase之间就是函数覆盖关系,Walk和Jump函数被派生类覆盖,输出肯定是派生类函数的输出;

2. CBase类处于作用域的外层,派生类的方法对于其将是不可见的,即隐藏的。而在派生类中,如果有重载函数时,基类函数将会被隐藏,否则基类函数就不被隐藏。

基类中void Run(int speed)与派生类中void Run(int speed)函数就是重载(overload)关系,当使用基类来调用派生类对象中重载函数,会根据其作用域来判断,如基类CBase,其作用域就是CBase这个类的大括号包含的内容,派生类CDeriverdA其作用域就是CDerivedA大括号中包含的内容。因此在使用基类调用派生类对象中的Run方法时,会执行基类的Run方法。

派生类中void Run(int speed, int direction) 是派生类中的重载方法,在基类是不能调用的。

 

你可能感兴趣的:(编程基础)