C++ 入門指南 4.01
練習 10.5 參考程式 - 練習設計整數計算類別
// 引入標準程式庫中相關的輸入、輸出程式
#include <iostream>
// std 為標準程式庫的命名空間
using namespace std;
// 宣告 IntegerDemo 類別
class IntegerDemo {
// 宣告 public 成員
public:
int value;
void Add(int);
void Subtract(int);
void Multiply(int);
void Divide(int);
};
// 實作 IntegerDemo 的 Add() 成員函數
void IntegerDemo::Add(int p) {
value += p;
}
// 實作 IntegerDemo 的 Subtract() 成員函數
void IntegerDemo::Subtract(int p) {
value -= p;
}
// 實作 IntegerDemo 的 Multiply() 成員函數
void IntegerDemo::Multiply(int p) {
value *= p;
}
// 實作 IntegerDemo 的 Divide() 成員函數
void IntegerDemo::Divide(int p) {
value /= p;
}
int main(void) {
// 宣告建立 IntegerDemo 物件
IntegerDemo a;
// 接收使用者輸入
int input1, input2;
cin >> input1 >> input2;
// 設定 value 及呼叫 Divide()
a.value = input1;
a.Divide(input2);
// 印出 value 成員變數
cout << endl;
cout << a.value << endl;
cout << endl;
// 最後回傳 0 給作業系統
return 0;
}
/* 《程式語言教學誌》的範例程式
http://kaiching.org/
檔名:exercise1005.cxx
編譯:g++ exercise1005.cxx
執行:./a.out
功能:C++入門指南單元十的練習
作者:張凱慶 */
回到練習題目