发现作为代码狗的我,时间久了,都快忘记了一些C++语言的基础知识,现在写篇文章记录一下,内容主要是涉及C++类的多态性,子类和父类的接口相互调用关系。即:
1、在子类中调用父类的接口(主要是重载接口),方式是父类::接口。
2、外部调用真实类的接口,方式是使用类的多态性实现,虚函数、加override实现。
3、在父类中调用子类多态性质的接口,方式是使用虚函数、加override实现,并给父类设置一个上下文。
具体代码如下:
#include <iostream>
class Parent
{
public:
Parent()
{
m_pInner = nullptr;
m_pCtx = nullptr;
}
virtual ~Parent() {}
public:
class Inner
{
public:
Inner()
{
m_pHolder = nullptr;
}
~Inner() {}
void setHolder(Parent* holder)
{
m_pHolder = holder;
return;
}
void test(int iVal)
{
m_pHolder->doSomethings(iVal); // 多态接口调用
return;
}
private:
Parent* m_pHolder = nullptr;
};
public:
void setInner(Inner* pInner)
{
m_pInner = pInner;
m_pInner->setHolder(this);
return;
}
void setCtx(Parent* parent)
{
m_pCtx = parent;
return;
}
virtual void doTest()
{
std::cout << "Parent, do test." << std::endl;
return;
}
virtual void doSomethings(int iVal)
{
std::cout << "Parent, do something, " << iVal << "." << std::endl;
return;
}
virtual void doCall()
{
std::cout << "Parent, do call." <<std::endl;
return;
}
void testCall()
{
m_pCtx->doCall(); // 调用真实的接口
return;
}
private:
Inner* m_pInner = nullptr;
Parent* m_pCtx = nullptr;
};
class Child : public Parent
{
public:
Child() {}
~Child() {}
void doTest()
{
std::cout << "Child, do test." << std::endl;
Parent::doTest(); // 调用父类的接口
return;
}
virtual void doSomethings(int iVal) override
{
std::cout << "Child, do something, " << iVal << "." << std::endl;
return;
}
virtual void doCall()
{
std::cout << "Child, do call." << std::endl;
return;
}
};
void testClass()
{
Parent::Inner inner;
Parent parent;
Child child;
// 测试类的多态调用
std::cout << "++++++++++++++++++++++++" << std::endl;
parent.setInner(&inner);
inner.test(123);
std::cout << "------------------------" << std::endl;
child.setInner(&inner);
inner.test(456);
// 测试子类调用父类接口
std::cout << "++++++++++++++++++++++++" << std::endl;
child.doTest();
// 测试父类调用子类接口
std::cout << "++++++++++++++++++++++++" << std::endl;
Parent* pInfo = new (std::nothrow) Child();
pInfo->setCtx(pInfo);
pInfo->doCall();
delete pInfo;
pInfo = nullptr;
std::cout << "------------------------" << std::endl;
pInfo = new (std::nothrow) Parent();
pInfo->setCtx(pInfo);
pInfo->doCall();
delete pInfo;
pInfo = nullptr;
std::cout << "++++++++++++++++++++++++" << std::endl;
return;
}
运行结果如下: