Struct inheritance in C++

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

Can a struct be inherited in C++?

6条回答
  •  借酒劲吻你
    2020-12-02 05:57

    In C++, a structure's inheritance is the same as a class except the following differences:

    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.

    // Program 1
    #include 
    
    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 
    
    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;
    }
    

提交回复
热议问题