C++ 入門指南 4.01
練習 12.8 參考程式 - 練習設計乒乓球類別的建構函數
// 引入標準程式庫中相關的輸入、輸出程式
#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());
}
// 宣告 Ball 類別
class Ball {
// 宣告 public 成員
public:
Ball(Point);
string get_p();
private:
Point p;
void set_p(Point);
};
// 實作建構函數
Ball::Ball(Point n) {
set_p(n);
}
// 實作 Ball 類別的 setter 成員函數
void Ball::set_p(Point n) {
p = n;
}
// 實作 Point 類別的 getter 成員函數
string Ball::get_p() {
return p.get_point();
}
int main(void) {
// 宣告建立 Point 物件
Point p(0 ,0);
// 宣告建立 Ball 物件
Ball b(p);
// 印出座標
cout << endl;
cout << b.get_p() << endl;
cout << endl;
// 最後回傳 0 給作業系統
return 0;
}
/* 《程式語言教學誌》的範例程式
http://kaiching.org/
檔名:exercise1208.cxx
編譯:g++ exercise1208.cxx
執行:./a.out
功能:C++入門指南單元十二的練習
作者:張凱慶 */
回到練習題目