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

1-The basic of Class #1

Open Pin-Jiun opened 1 year ago

Pin-Jiun commented 1 year ago

為什麼需要有物件(Object)?

1960年代程式設計領域正面臨著一種危機:在軟硬體環境逐漸複雜的情況下,軟體如何得到良好的維護? 物件導向程式設計解決了這一問題,性並衍伸出許多物件特有的能力

在C語言中,假設要建立儲存班上每個學生的資料,需要使用 structure 進行儲存維護

struct student{ 
    int id; 
    char *name;
    int age; 
    float score;
}Amy, John;  //直接在structure後面進行宣告

再分別填入Amy, John等人的相關資料

但假設今天人數很多,其資料維護就會有困難,此時就需要 物件 進行更彈性的維護

Class

class Student{
public:
  string Name;
  int Age;
  void Print(){
    cout << "Object " << this->Name <<" is constructed.\n";  
  }
};

this表示此物件的指標,通常this可以省略不寫

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

在class中會有許多的 成員member ,其中member包刮:

  1. 屬性 attribute -class內的基本的資料,例如String Name
  2. 方法 method -class內的function

建立Jim Student這個物件,並賦值

    Student Jim;
    Jim.Name =  "Pin-Jiun";
    Jim.Age = 20;
    Jim.Print();

完整程式碼如下

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

class Student{
public:
  string Name;
  int Age;
  void Print(){
    cout << "Object " << Name <<" is constructed.\n";  
  }
};

int main()
{
    Student Jim;
    Jim.Name =  "Pin-Jiun";
    Jim.Age = 20;
    Jim.Print();
    return 0;
}

constructor 建構子

假設我們今天有100位學生資料,那我們不就要建立100個student物件,並分別賦值? 為了解決上述問題,這時候就需要 constructor 建構子 ,constructor可以在建構的時候就進行賦值動作

使用constructor有以下幾個規則

  1. 使用的名稱須和class的名稱相同
  2. constructor無回傳值
  3. 需要是public成員
  4. constructor 可以有多個,系統會自行判定傳入的參數
#include <iostream>
#include <string>
using namespace std;

class Student{
public:
  string Name;
  int Age;
  void Print(){
    cout << "Object " << Name <<" is constructed.\n";  
  }

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

  Student(string name){
      Name=name;
      Age = 18;
  }
};

int main()
{
    // Student Jim; >>無法使用此
    //因為有自行宣告的constructor,建立的時候要賦值
    Student Jim("Pin-Jiun",20);
    Jim.Print();

    Student Amy("Amy");
    Amy.Print();
    return 0;
}