Struct inheritance in C++

后端 未结 6 655
情书的邮戳
情书的邮戳 2020-12-02 05:28

Can a struct be inherited in C++?

6条回答
  •  生来不讨喜
    2020-12-02 05:54

    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

    #include
    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 = C.a;
            b = C.b;
            data = C.data;
        }
    };
    int main()
    {
       child c1 ,
             c2(10 , 20),
             c3(10 , 20, 30),
             c4(c3);
    
        auto print = [](const child &c) { cout<

提交回复
热议问题