为什么我们不能在继承中更改基类中函数的访问级别?

时间:2015-10-25 14:58:05

标签: c++ inheritance polymorphism

在下面的代码中,如果基类派生为protected,则代码不起作用。为什么? 什么时候保护和私有访问说明符在继承具有虚函数的基类时使用? 此外,由于子类可以访问父类,为什么基类的指针指向它的父类? 通过以下代码来理解这些问题。

#include<iostream>
using namespace std;

class A
{
public:
    virtual void show()
    {
    cout<<"In A"<<endl;
    }
};
class B:public A//--QUESTION-----Making A protected is giving an error. Why?
{
public:
//protected: works..
    void show()
    {
        cout<<"In B"<<endl;
    }
};
class C : public B//Making B protected is giving an error. Why?
{
public:
     void show()
    {
        cout<<"In C"<<endl;
    }
};
int main()
{
    A obj1;
    B obj2;
    C obj3;
    A *obj;
    B *objp;
    C *objp3;
    obj=&obj2;
    obj->show();

    /*The following 4 lines also do not work. Since a child class has access to parent class, why can't a pointer of base class point to its parent class?*/
    //objp3=&obj2;
    //objp3->show();
    objp=&obj1;
    objp->show();
}

编辑:但是我们可以覆盖变量的访问级别,那为什么不能运行?也正在使void show()虚拟对其产生影响吗?

1 个答案:

答案 0 :(得分:0)

如果您从Aprotected派生,则您将A的所有内容设为publicprotected

class B:protected A
{
public:
//protected: works..
    void show()
    {
        cout<<"In B"<<endl;
    }
};

因此,课程B现在继承void show(),即使show() public Aprotected也是void show(),继承的protected现在也是B。在您的继承类void show()中,您现在正试图覆盖C的非法访问级别。同样适用于app.use(function(req, res, next) { // open connection req.db = db; next(); }); then use it in route. var dbs = req.db;