Class vs Struct for data only?

后端 未结 7 758
暖寄归人
暖寄归人 2020-11-28 15:35

Is there any advantage over using a class over a struct in cases such as these? (note: it will only hold variables, there will never be functions)

class Foo         


        
7条回答
  •  无人及你
    2020-11-28 16:15

    One side point is that structs are often used for aggregate initialized data structures, since all non-static data members must be public anyway (C++03, 8.5.1/1).

    struct A {  // (valid)
    {
       int a;
       int b;
    } x = { 1, 2 };
    
    struct A {  // (invalid)
    private:
       int a;
       int b;
    } x = { 1, 2 };
    
    class A {  // (invalid)
       int a;
       int b;
    } x = { 1, 2 };
    
    class A {  // (valid)
    public:
       int a;
       int b;
    } x = { 1, 2 };
    
    class A {  // (invalid)
    public:
       int a;
    private:
       int b;
    } x = { 1, 2 };
    

提交回复
热议问题