将基类中的虚函数定义为public,在派生类中将该虚函数定义为private,则可以通过基类指针调用派生类的private函数
#include <iostream>
#include <string>
#include <memory>
class BaseA
{
int data;
std::string msg;
public:
BaseA() {
msg="BaseA message";
}
virtual ~BaseA() {
std::cout<<__FUNCTION__<<std::endl;
}
virtual void show_msg() {
std::cout<<msg<<std::endl;
}
};
class DeriveA:public BaseA
{
int data;
std::string msg;
public:
DeriveA() {
msg="DeriveA message";
}
~DeriveA() {
std::cout<<__FUNCTION__<<std::endl;
}
private:
void show_msg() {
std::cout<<msg<<std::endl;
}
};
void UsePrivateFunc() {
std::shared_ptr<BaseA> sptr_BaseA(new DeriveA());
sptr_BaseA->show_msg();
}
int main(int argc,char* argv[])
{
UsePrivateFunc();
return 0;
}
运行结果