C++多继承、虚函数内存

举例

class A从 class IBase,class IProxyBase继承,具体参看后文测试代码。

示意图

C++多继承、虚函数内存_第1张图片

测试代码

#include 

class IBase
{
public:
	virtual void FunA() = 0;
	virtual void FunB() = 0;
	virtual void FunC() = 0;
};

class IProxyBase
{
public:
	virtual void ProxyFunA() = 0;
	virtual void ProxyFunB() = 0;
	virtual void ProxyFunC() = 0;
};

class A : public IBase, public IProxyBase
{
public:
	A() :m_nValue(3){}

	virtual ~A(){}

	virtual void FunA() override
	{
		std::cout << __FUNCTION__ << std::endl;
	}
	virtual void FunB() override
	{
		std::cout << __FUNCTION__ << std::endl;
	}
	virtual void FunC() override
	{
		std::cout << __FUNCTION__ << std::endl;
	}


	virtual void ProxyFunA() override
	{
		std::cout << __FUNCTION__ << std::endl;
	}
	virtual void ProxyFunB() override
	{
		std::cout << __FUNCTION__ << std::endl;
	}
	virtual void ProxyFunC() override
	{
		std::cout << __FUNCTION__ << std::endl;
	}

private:
	int m_nValue;
};




int main(int argc, char** argv)
{
	A* pA = new A();

	std::cout << sizeof(A) << std::endl;

	IBase* pBase = pA; //pBase指向pA
	IProxyBase* pProxyBase = pA; //pProxyBase指向pA+4, +4是因为此4字节为IBase的虚函数指针大小,参看上文示意图

	pBase->FunA();
	pProxyBase->ProxyFunA();


	//强转后,函数指针指向的还是ProxyFuncA, 所以此处调用的还是ProxyFuncA
	reinterpret_cast<IBase*>(pProxyBase)->FunA();


	return 0;
}

运行截图

C++多继承、虚函数内存_第2张图片

你可能感兴趣的:(C/C++,虚函数)