C++ 入門指南 4.01

練習 10.3 參考程式 - 練習設計整數計算類別

// 引入標準程式庫中相關的輸入、輸出程式
#include <iostream>

// std 為標準程式庫的命名空間
using namespace std;

// 宣告 IntegerDemo 類別
class IntegerDemo {
// 宣告 public 成員
public:
    int value;
    void Add(int);
    void Subtract(int);
};

// 實作 IntegerDemo 的 Add() 成員函數
void IntegerDemo::Add(int p) {
    value += p;
}

// 實作 IntegerDemo 的 Subtract() 成員函數
void IntegerDemo::Subtract(int p) {
    value -= p;
}

int main(void) {
    // 宣告建立 IntegerDemo 物件
    IntegerDemo a;

    // 接收使用者輸入
    int input1, input2;
    cin >> input1 >> input2;

    // 設定 value 及呼叫 Subtract()
    a.value = input1;
    a.Subtract(input2);

    // 印出 value 成員變數
    cout << endl;
    cout << a.value << endl;
    cout << endl;

    // 最後回傳 0 給作業系統
    return 0;
}

/* 《程式語言教學誌》的範例程式
   http://kaiching.org/
   檔名:exercise1003.cxx
   編譯:g++ exercise1003.cxx
   執行:./a.out
   功能:C++入門指南單元十的練習
   作者:張凱慶 */
回到練習題目

上一頁 練習 10.2 參考程式 - 練習設計整數計算類別
回 C++ 入門指南 4.01 目錄
下一頁 練習 10.4 參考程式 - 練習設計整數計算類別
回 C++ 教材
回程式語言教材首頁