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