[C++] The difference between Structure and Class

发布于 2024-03-19  332 次阅读


Please refresh the page if equations are not rendered correctly.
---------------------------------------------------------------

Code with explanation

// Structure and class difference

#include <iostream>

using namespace std;

/* Structure - a data container */
// Small passive objects that carry public data and have no or few basic member functions.
// Data members are typically public (i.e., can be accessed by any function) and 
// are accessed using the direct member access operator (.).
struct Person_struct {
    string name;
    int age;
    void print() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

/* Class - complex data structure */
// Active objects that carry private data, interfaced through public member functions.
// A class is a user-defined data type that we can use in our program, and it works
// as an object constructor, or a "blueprint" for creating objects.
// Data members are typically private (i.e., can be accessed only by member functions)
// and are accessed using the member access operator (->).
// Class data are usually named with a trailing underscore (_).
class Person_class {
    string name_;
    int age_;
  public:
    void set_name(string n) { // Mutator/setter function
        name_ = n;
    }
    void set_age(int a) {
        age_ = a;
    }
    void print() {
        cout << "Name: " << name_ << ", Age: " << age_ << endl;
    }

    unsigned age() const { return age_; }  // Accessor/getter function
};

int main() {
    cout << "Structure and class difference" << endl;
    cout << "==============================" << endl;
    Person_struct p1;
    p1.name = "John";
    p1.age = 25;
    p1.print();

    Person_class p2;
    p2.set_name("John Class");
    p2.set_age(20);
    p2.print();

    cout << "p2.age: " << p1.age_ << endl;
    return 0;
}

Summary

  1. Use struct for passive objects with public data, and use class for active objects with private data.
  2. Use class with mutator and accessor functions to control changes to the data.
  3. Avoid making mutator and accessor functions if possible.
届ける言葉を今は育ててる
最后更新于 2024-03-19