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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:12:59  来源:igfitidea点击:

Struct inheritance in C++

c++inheritancestruct

提问by Alex Martelli

Can a structbe inherited in C++?

可以struct在 C++ 中继承吗?

回答by Alex Martelli

Yes, structis exactly like classexcept the default accessibility is publicfor struct(while it's privatefor class).

是的,除了默认的可访问性是for (而它是for )之外,struct完全一样。classpublicstructprivateclass

回答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;
}