標籤

bat (52) 作品 (38) python (21) shell (17) windows (11) 虛擬機 (11) php (10) CPP (6) KMS (6) 程式設計 (6) docker (5) 使用教學 (5) xoops (4) 公文 (4) Apache2 (3) Excel (3) juniper (3) 資料庫 (3) mysql (2) 免動手 (2) 資料結構 (2) 軟體廣播 (2) 電腦維修 (2) Android Studio (1) Apple IPAD管理 (1) Arduino (1) CSS (1) LAMP (1) NAS (1) Ubuntu (1) VHD (1) Windows Server (1) 原因 (1) 程式應用 (1) 程式積木 (1) 編輯器 (1) 雲端硬碟 (1)

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;
}



沒有留言:

張貼留言

只要點兩下,傳統右鍵選單改回Win11右鍵選單

系列文章: 1. 只要點兩下,就能將Win11 右鍵選單 回復 傳統右鍵選單 2. 只要點兩下,傳統右鍵選單改回Win11右鍵選單 上一篇提到只要點兩下,就能將Win11選單回到傳統選單。但是有沒有方法能夠回到Win11選單呢?                    ...