Pin-Jiun / Programming-Language-CPP

It's the note/experience about C++, and I have the basic ability of C.
0 stars 0 forks source link

2-Encapsulation #2

Open Pin-Jiun opened 1 year ago

Pin-Jiun commented 1 year ago

封裝(Encapsulation)

將成員依照各種程度的隱私組合起來,僅對外公開部分資訊,達到 隱藏資料 以及 保護程式資料免於產生bug 的功能

C++三種封裝程度修飾字

C++物件和structure最不同的地方, class的宣告default是private ,而structure是public

以下是範例

#include <iostream>
#include <string>
using namespace std;

class Student{
private:
  string Name;
  int Age;

public:  
  //constructor
  Student(string name, int age){
    Name = name;
    Age = age;
  }

  void Print(){
    cout << "Object " << Name <<" is constructed.\n";  
  }
};

int main()
{
    Student Jim("Pin-Jiun",20);
    Jim.Print();

    return 0;
}

Getter、Setter

如果有些資料的設定或查閱需要進行檢查的,則此時可以進行封裝 例如以下的GetGPA()SetGPA 正常而言,學生的GPA是要<4.0的,可以使用封裝進行基本的設定

#include <iostream>
#include <string>
using namespace std;

class Student{
private:
  string Name;
  int Age;
  float GPA;

public:  
  //constructor
  Student(string name, int age){
    Name = name;
    Age = age;
  }

  float GetGPA(){
      return GPA;
  }

  void SetGPA(float gpa){
      if (gpa<=4.00) GPA = gpa;
      else cout << "Wrong number, please reenter the number\n";
  }
};

int main()
{
    Student Jim("Pin-Jiun",20);
    Jim.SetGPA(3.9);

    return 0;
}