码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-11-06 12:13:16      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:ios   namespace   str   问题   ase   end   函数重写   private   理解   

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++虚函数重写的权限问题

标签:ios   namespace   str   问题   ase   end   函数重写   private   理解   

原文地址:http://www.cnblogs.com/invisible2/p/7792421.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!