受保护的派生类 [英] Protected derived class

查看:123
本文介绍了受保护的派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include< iostream> 
using namespace std;

class Base
{
public:
Base(){cout<<Base<< endl;}
virtual~ Base(){cout<<〜Base<< endl;}
virtual void foo(){cout<<foo base<< endl;}
};

class派生:私人基础
{
public:
Derived(){cout<<Derived<< endl;}
virtual~Derived(){cout<<~Derved<< endl;}
virtual void foo(){cout<<foo dervied<< endl;}
};


int main(int argc,char * argv [])
{
Base * pb = new Derived;
派生d;
d.foo();
返回0;
}

当我执行上面的示例程序时出现以下错误:
protected.cpp:在函数'int main(int,char **)'中:
protected.cpp:26:错误:'Base'是'Derived'无法访问的基础



为什么不可能用基指针创建Derived对象????






所以我可以创建Derived类的实例,如

 派生d 
派生d1 = new派生;

但是从Base类指针创建实例,如

 基数* b =新派生

将失败。



这是因为Derived不是来自Base的派生类,当派生和私有派生时?



这是正确?????

解决方案


为什么无法使用基指针创建Derived对象? ?????? b
$ b $ p

因为基数是 private 。这明确禁止从外部将您的类视为 Base 实例。从外部看,您的类派生 Base 的子类,仅来自在类本身内部。



protected 继承的计数相同,唯一的区别是基类现在不是不再属于自己的类,而是属于任何派生类。但到了外面,它的行为就像私人继承一样。


 #include <iostream>
using namespace std;

class Base
{
    public:
        Base(){cout <<"Base"<<endl;}
        virtual ~Base(){cout<<"~Base"<<endl;}
        virtual void foo(){ cout<<"foo base"<<endl;}
};

class Derived: private Base
{
    public:
        Derived(){cout<<"Derived"<<endl;}
        virtual ~Derived(){cout<<"~Derived"<<endl;}
        virtual void  foo(){ cout<<"foo dervied"<<endl;}
};


int main(int argc, char *argv[])
{
    Base *pb = new Derived;
    Derived d;
    d.foo();
    return 0;
}

when I execute the above sample program I get following error: protected.cpp: In function ‘int main(int, char**)’: protected.cpp:26: error: ‘Base’ is an inaccessible base of ‘Derived’

Why its not possible to create Derived object with base pointer????


So I can create an instanse of Derived class like

Derived d
Derived d1= new Derived;

But creating instance from Base class pointer like

Base * b = new derived 

will fail.

This is because Derived is not actaully a derived class from Base when derived procted and privately??

Is this correct?????

解决方案

Why its not possible to create Derived object with base pointer????

Because the base is private. This explicitly forbids treating your class as a Base instance from the outside. Seen from the outside, your class Derived is not a subclass of Base, only from inside the class itself.

The same counts for protected inheritance, with the only difference that the base class now isn't private to the own class any more but rather to any derived class as well. To the outside though, it behaves just like private inheritance.

这篇关于受保护的派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆