將基類中的虛函數定義為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;
}
運行結果
