2021年7月2日 星期五

C++ Class 的範例筆記

程式名稱:ClassRectangle01.cpp
程式內容:

#include <iostream>
using namespace std;

class CRectangle {
int x,y;
  public:
     void set_values (int a,int b) {
        x = a;
y = b;
}
     int area(void){
      return x*y;
}
};

int main() {

  CRectangle rect;
  rect.set_values(3,4);
  cout << " area: " << rect.area();
}

建構子
建構子 constructor, 它透過一個與 class 同名的函數來定義。當且僅當要生成一個 class 的新的物件的 時候或給該 class 的一個物件分配記憶體的時候,這個建構子將自動被調用。。一個建構子永遠沒有返回值,也不用宣告成 void。

程式名稱:ClassRectangle02.cpp
程式內容:
#include <iostream>
using namespace std;

class CRectangle {
int width,height;
public:
CRectangle (int a, int b) {
width = a;
height = b;
}
int area(void) {
return width*height;
};

int main() {
CRectangle rect01 (3,4),rect02 (5,6);
        cout << " rect01 area:" << rect01.area()<< endl;
        cout << " rect02 area:" << rect02.area()<< endl;
}

解構子
解構子 destructor 完成相反的功能。它在 objects 被從記憶體中釋放的時候被自動 調用。釋放可能是因為它存在的範圍已經結束了(例如,如果 object 被定義為一 個函數內的 local (區域) 物件變數,而該函數結束了);或者是因為它是一個動 態分配的物件,而被使用運算子 delete 釋放了。 解構子必頇與 class 同名,加上水波號 tilde (~) 首碼,一樣必頇無返回值

程式名稱:ClassRectangle03.cpp
程式內容:
#include <iostream>

using namespace std;

class CRectangle {
int *width,*height;
public:
CRectangle (int a, int b) {
width = new int;
height = new int;
*width = a;
*height = b;
}
~CRectangle (){
delete width;
delete height;
}; 
int area(void) {
return *width * *height;
};

int main() {
CRectangle rect01 (3,4),rect02 (5,6);
    cout << " rect01 area:" << rect01.area()<< endl;
    cout << " rect02 area:" << rect02.area()<< endl;
}



沒有留言:

張貼留言

只要點兩下,就可以將資料夾input內的所有Word通通轉成一個PDF

系列文章: 1. python 不管何時何地,只要點兩下,資料夾內的所有pdf都會合併成一個pdf https://skjhcreator.blogspot.com/2022/06/pythonpdfpdf.html 2. python 只要點兩下,分別對各資料夾內的pdf合併,...