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