C++中的结构继承
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/979211/
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
Struct inheritance in C++
提问by Alex Martelli
Can a struct
be inherited in C++?
可以struct
在 C++ 中继承吗?
回答by Alex Martelli
Yes, struct
is exactly like class
except the default accessibility is public
for struct
(while it's private
for class
).
是的,除了默认的可访问性是for (而它是for )之外,struct
完全一样。class
public
struct
private
class
回答by Suvesh Pratapa
Yes. The inheritance is public by default.
是的。继承默认是公开的。
Syntax (example):
语法(示例):
struct A { };
struct B : A { };
struct C : B { };
回答by Chad Gorshing
Other than what Alex and Evan have already stated, I would like to add that a C++ struct is not like a C struct.
除了 Alex 和 Evan 已经说过的,我想补充一点,C++ 结构不像 C 结构。
In C++, a struct can have methods, inheritance, etc. just like a C++ class.
在 C++ 中,结构可以像 C++ 类一样具有方法、继承等。
回答by Evan Teran
Of course. In C++, structs and classes are nearly identical (things like defaulting to public instead of private are among the small differences).
当然。在 C++ 中,结构和类几乎相同(例如默认为 public 而不是 private 是一些细微的差异)。
回答by Neha Agrawal
In C++, a structure's inheritance is the same as a class except the following differences:
在 C++ 中,结构的继承与类相同,但有以下区别:
When deriving a struct from a class/struct, the default access-specifier for a base class/struct is public. And when deriving a class, the default access specifier is private.
从类/结构派生结构时,基类/结构的默认访问说明符是公共的。并且在派生类时,默认访问说明符是私有的。
For example, program 1 fails with a compilation error and program 2 works fine.
例如,程序 1 因编译错误而失败,而程序 2 工作正常。
// Program 1
#include <stdio.h>
class Base {
public:
int x;
};
class Derived : Base { }; // Is equivalent to class Derived : private Base {}
int main()
{
Derived d;
d.x = 20; // Compiler error because inheritance is private
getchar();
return 0;
}
// Program 2
#include <stdio.h>
struct Base {
public:
int x;
};
struct Derived : Base { }; // Is equivalent to struct Derived : public Base {}
int main()
{
Derived d;
d.x = 20; // Works fine because inheritance is public
getchar();
return 0;
}