简体   繁体   English

C++中的结构继承

[英]Struct inheritance in C++

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

是的, structclass完全一样,除了默认的可访问性对于structpublic (而对于classprivate的)。

Yes.是的。 The inheritance is public by default.继承默认是公开的。

Syntax (example):语法(示例):

struct A { };
struct B : A { };
struct C : B { };

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++ 类一样具有方法、继承等。

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

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 是一些细微的差异)。

Yes, c++ struct is very similar to c++ class, except the fact that everything is publicly inherited, ( single / multilevel / hierarchical inheritance, but not hybrid and multiple inheritance ) here is a code for demonstration是的,c++ struct 与c++ class 非常相似,除了所有内容都是公开继承的,(单/多级/分层继承,但不是混合和多继承)这里是演示代码

 #include<bits/stdc++.h> using namespace std; struct parent { int data; parent() : data(3){}; // default constructor parent(int x) : data(x){}; // parameterized constructor }; struct child : parent { int a , b; child(): a(1) , b(2){}; // default constructor child(int x, int y) : a(x) , b(y){};// parameterized constructor child(int x, int y,int z) // parameterized constructor { a = x; b = y; data = z; } child(const child &C) // copy constructor { a = Ca; b = Cb; data = C.data; } }; int main() { child c1 , c2(10 , 20), c3(10 , 20, 30), c4(c3); auto print = [](const child &c) { cout<<ca<<"\\t"<<cb<<"\\t"<<c.data<<endl; }; print(c1); print(c2); print(c3); print(c4); } OUTPUT 1 2 3 10 20 3 10 20 30 10 20 30

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM