• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
invisible_man
博客园    首页    新随笔    联系   管理    订阅  订阅

c++虚函数重写的权限问题

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,...)



posted @ 2017-11-06 11:53  invisible_man  阅读(242)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3