C++ 入門指南 4.01
練習 10.9 參考程式 - 練習設計平面座標類別
// 引入標準程式庫中相關的輸入、輸出程式
#include <iostream>
// 使用絕對值函數 abs()
#include <cmath>
// std 為標準程式庫的命名空間
using namespace std;
// 宣告 Point 類別
class Point {
// 宣告 public 成員
public:
int x, y;
int Distance(Point);
};
// 實作 Point 的 Distance() 成員函數
int Point::Distance(Point p) {
return abs(p.x - x) + abs(p.y - y);
}
int main(void) {
// 設定兩個座標點
Point a, b;
a.x = 1;
a.y = 2;
b.x = 10;
b.y = 11;
// 印出兩點距離
cout << endl;
cout << a.Distance(b) << endl;
cout << endl;
// 最後回傳 0 給作業系統
return 0;
}
/* 《程式語言教學誌》的範例程式
http://kaiching.org/
檔名:exercise1009.cxx
編譯:g++ exercise1009.cxx
執行:./a.out
功能:C++入門指南單元十的練習
作者:張凱慶 */
回到練習題目