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

后端 未结 25 1686
误落风尘
误落风尘 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:42

    Technically both are the same in C++ - for instance it's possible for a struct to have overloaded operators etc.

    However :

    I use structs when I wish to pass information of multiple types simultaneously I use classes when the I'm dealing with a "functional" object.

    Hope it helps.

    #include 
    #include 
    using namespace std;
    
    struct student
    {
        int age;
        string name;
        map grades
    };
    
    class ClassRoom
    {
        typedef map student_map;
      public :
        student getStudentByName(string name) const 
        { student_map::const_iterator m_it = students.find(name); return m_it->second; }
      private :
        student_map students;
    };
    

    For instance, I'm returning a struct student in the get...() methods over here - enjoy.

提交回复
热议问题