本文介绍了默认类继承访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个基础和派生类:

  class Base 
{
public:
virtual void Do();
}

class Derived:Base
{
public:
virtual void Do();
}

int main()
{
Derived sth;
sth.Do(); // calls Derived :: Do OK
sth.Base :: Do(); // ERROR;不调用Based :: Do
}

如果我希望访问Base :: Do通过Derived。当我声明Derive为

 时,我得到一个编译错误class Base in unrecessibleclass Derived:public Base $ b $ 



我已读取默认继承

解决方案

您可能读过不完整或误导的内容。引用Bjarne Stroustrup从C ++编程语言,第四版,p。 602:

这也适用于没有访问级别说明符的继承成员。



只使用struct来组织纯数据成员。您正确地使用了来建模和实现对象行为。


Suppose I have a base and derived class:

class Base
{
    public:
    virtual void Do();
}

class Derived:Base
{
    public:
    virtual void Do();
}

int main()
{
    Derived sth;
    sth.Do(); // calls Derived::Do OK
    sth.Base::Do(); // ERROR; not calls Based::Do
}

as seen I wish to access Base::Do through Derived. I get a compile error as "class Base in inaccessible" however when I declare Derive as

class Derived: public Base

it works ok.

I have read default inheritance access is public, then why I need to explicitly declare public inheritance here?

解决方案

You might have read something incomplete or misleading. To quote Bjarne Stroustrup from "The C++ programming Language", fourth Ed., p. 602:

This also holds for members inherited without access level specifier.

A widespread convention is, to use struct only for organization of pure data members. You correctly used a class to model and implement object behaviour.

这篇关于默认类继承访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:56