将基类中的虚函数定义为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;
}

运行结果

在类的外面调用类的private函数

相关文章:

  • 2021-06-19
  • 2021-11-13
  • 2022-12-23
  • 2021-07-30
  • 2021-10-24
  • 2022-02-08
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-19
  • 2022-12-23
  • 2022-01-12
相关资源
相似解决方案