美文网首页C++
class VS struct(c++)

class VS struct(c++)

作者: Kai_Z | 来源:发表于2018-03-14 10:49 被阅读5次

    简介

    本文主要介绍在C++中structclass的主要区别

    默认访问权限

    • class的默认访问权限是private
    • struct的默认访问权限是public

    例程

    #include <iostream>
    class CTest
    {
        int class_member; //默认访问属性:private
    };
    struct STest
    {
        int struct_member; //默认访问属性:public
    };
    int main()
    {
        CTest classTest;
        STest structTest;
            //提示错误:member "CTest::class_member" is inaccessible
        //classTest.class_member = 30; 
        structTest.struct_member = 10;
        std::cout << "struct's member: " << structTest.struct_member << "\n";
        system("pause");
        return 0;
    }
    输出值:
    struct's member: 10
    

    默认的继承访问权限

    • class的默认继承访问权限是private
    • struct的默认继承访问权限是public

    例程

    #include <iostream>
    class CTest
    {
      public:
        int class_member;
    };
    
    class CDerived :CTest // default access specifier is private
    {
    };
    
    struct STest
    {
        int struct_member;
    };
    
    struct SDerived :STest //defautl access specifier is public
    {
    };
    
    
    int main()
    {
        SDerived s_derived;
        CDerived c_derived;
        s_derived.struct_member = 100;
        //Error:class "CDerived" has no member "struct_member"
        // because default access specifier is private for class
        //c_derived.struct_member = 200;
        std::cout << "s_derived.struct_member= " << s_derived.struct_member << "\n";
        return 0;
    }
    //输出结果
    s_derived.struct_member= 100
    

    struct与class之间混合继承

    1. 什么是混合继承?
      答:好吧,这是我自己想的,指通过struct去继承class,或通过class去继承struct
    • 通过struct默认继承class,继承方式为public继承
    • 通过class默认继承struct,继承方式为private继承

    例程

    #include <iostream>
    class CTest
    {
    public:
        int class_member;
    };
    
    struct SDerivedClass :CTest // 相当于 struct sDerivedClass: public CTest{};
    {
    };
    
    struct STest
    {
        int struct_member;
    };
    
    class CDerivedStruct :STest // 相当于class CDerivedStruct: private STest{};
    {
    };
    
    int main()
    {
        SDerivedClass sDerived;
        CDerivedStruct cDerived;
        sDerived.class_member = 100;
        //Error: "struct_member" is not a member of "CDerived"
        //cDerived.struct_member = 200;
        std::cout << "sDerived.class_member: " << sDerived.class_member << "\n";
        return 0;
    }
    输出结果:
    sDerived.class_member: 100
    

    相关文章

      网友评论

        本文标题:class VS struct(c++)

        本文链接:https://www.haomeiwen.com/subject/ykxzfftx.html