在類的外面調用類的private函數


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

運行結果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM