默认类继承访问 [英] Default class inheritance access

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

问题描述

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

  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:


中,成员默认为 private ;在 struct 中,成员
默认为 public (§16.2.4)。


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



只使用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:

In a class, members are by default private; in a struct, members are by default public (§16.2.4).

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.

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

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