C++ 默认类继承访问
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3811424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Default class inheritance access
提问by paul simmons
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
正如所见,我希望通过派生访问 Base::Do。但是,当我将 Derive 声明为
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?
我已经读过默认继承访问是公共的,那为什么我需要在这里显式声明公共继承?
采纳答案by Peter G.
You might have read something incomplete or misleading. To quote Bjarne Stroustrup from "The C++ programming Language", fourth Ed., p. 602:
您可能阅读了不完整或误导性的内容。引用 Bjarne Stroustrup 中的“C++ 编程语言”,第四版,p。602:
In a
class
, members are by defaultprivate
; in astruct
, members are by defaultpublic
(§16.2.4).
在 a 中
class
,成员是默认的private
;在 a 中struct
,成员默认为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.
一个普遍的约定是,仅将 struct 用于组织纯数据成员。您正确使用 aclass
来建模和实现对象行为。
回答by liaK
From standard docs, 11.2.2
来自标准文档,11.2.2
In the absence of an access-specifier for a base class, publicis assumed when the derived class is defined with the class-keystructand privateis assumed when the class is defined with the class-keyclass.
在没有访问说明符为基类的,公共当派生的类与定义的假定 的类键结构和私人当类与定义的假定的类键类。
So, for struct
s the default is public
and for class
es, the default is private
...
因此,对于struct
s,默认值为public
,对于class
es,默认值为private
...
Examples from the standard docs itself,
标准文档本身的示例,
class D3 : B { / ... / }; // B private by default
class D3 : B { / ... / }; // B private by default
struct D6 : B { / ... / }; // B public by default
struct D6 : B { / ... / }; // B public by default
回答by Prasoon Saurav
The default inheritance level (in absence of an access-specifier for a base class )for class
in C++ is private. [For struct
it is public]
class
C++ 中的默认继承级别(在没有基类的访问说明符的情况下)是私有的。[因为struct
它是公开的]
class Derived:Base
class Derived:Base
Base
is privately inherited so you cannot do sth.Base::Do();
inside main()
because Base::Do()
is private inside Derived
Base
是私人继承的,所以你不能在sth.Base::Do();
里面做,main()
因为里面Base::Do()
是私有的Derived
回答by Dev
The default type of the inheritance is private. In your code,
继承的默认类型是私有的。在您的代码中,
class B:A
B级:A
is nothing but
无非是
class B: private A
B类:私人A