1. 程式人生 > >c++虛函數重寫的權限問題

c++虛函數重寫的權限問題

spa static mes ptr cast str iostream 調用 函數

cbase.h:

 #ifndef CBASE_H

#define CBASE_H
#include<iostream>
using std::cout;
using std::endl;
class CBase{
public:
    virtual void show();
};
#endif // CBASE_H

cbase.cpp:
#include"cbase.h"
void CBase::show()
{
    cout<<"CBase"<<endl;
}

cderived.h:
#ifndef CDERIVED_H
#define CDERIVED_H
#include"cbase.h"
class CDerived:public CBase{
private:
    void show() override;
};
#endif // CDERIVED_H

cderived.cpp:
#include"cderived.h"
void CDerived::show()
{
    cout<<"CDerived"<<endl;
}

main.cpp:
#include <iostream>
#include"cderived.h"
using namespace std;

int main()
{
    CBase* pBase=new CDerived;
    pBase->show();
    dynamic_cast<CDerived*>(pBase)->show();
    delete pBase;

    CDerived* pDerived=new CDerived;
    pDerived->show();
    static_cast<CBase*>(pDerived)->show();
    delete pDerived;
return 0
}
程序運行會報錯:dynamic_cast<CDerived*>(pBase)->show();pDerived->show();
說是私有的不可調用
可見編譯器只看到了他所看到的,要從編譯器的角度看問題。只是把指針是什類型就是什麽類型。理解(*(p->vptr)[n])(p,...)


c++虛函數重寫的權限問題