When should you use a class vs a struct in C++?

后端 未结 25 1713
误落风尘
误落风尘 2020-11-22 00:18

In what scenarios is it better to use a struct vs a class in C++?

25条回答
  •  面向向阳花
    2020-11-22 00:53

    Class.

    Class members are private by default.

    class test_one {
        int main_one();
    };
    

    Is equivalent to

    class test_one {
      private:
        int main_one();
    };
    

    So if you try

    int two = one.main_one();
    

    We will get an error: main_one is private because its not accessible. We can solve it by initializing it by specifying its a public ie

    class test_one {
      public:
        int main_one();
    };
    

    Struct.

    A struct is a class where members are public by default.

    struct test_one {
        int main_one;
    };
    

    Means main_one is private ie

    class test_one {
      public:
        int main_one;
    };
    

    I use structs for data structures where the members can take any value, it's easier that way.

提交回复
热议问题