C++

C++实验(五):设计Point类

Posted by HK on May 22, 2019

实验要求

问题描述

计算机的显示屏的坐标系是这样的,左上角的坐标为(0,0),如下图所示。

等待网络加载图片···

定义计算机显示屏上的点Point类。该类具有两个私有数据成员x、y,分别表示该点的横坐标、纵坐标。类的声明如下:

class Point {
public:
// 默认构造函数,默认值为左上角坐标(0, 0)

Point(int x = 0, int y = 0);
void setX(int x);
int getX();
void setY(int y);
int getY();
void print();
void moveRight(int offset);
void moveDown(int offset);
private:
int x;
int y;
};

问题要求

请实现以下函数声明,要求能得到如下图所示的运行结果。

(1)接受用户的输入,生成两个对象。

(2)打印这两个点。

(3)向右平移其中一个点后,打印该点。向下平移另一个点后,打印该点。

运行结果示例

Please input a point: 12 8

Point p1: (12, 8)

Point p2: (24, 16)

After moving right, p1: (22, 8)

After moving down, p2: (24, 6)

实验代码及结果

#include<iostream>

using namespace std;

class Point {
public:       //外部接口

	Point(int xx = 0, int yy = 0) {     //构造函数

		x = xx;
		y = yy;
	}
	void print() {
		cout << "(" << getX() << "," << getY() << ")" << endl;
	}

	int getX() {     //得到数据x

		return x;
	}
	int getY() {     //得到数据y

		return y;
	}
	void moveRight(int offset) {   //改变x的值

		x = x + offset;
	}

	void moveDown(int offset) {    //改变y的值

		y = y + offset;
	}

private:                                     
	int x;
	int y;
};


int main()
{
	int x, y;
	cout << "Please input a point:";
	cin >> x >> y;
	Point p1(x, y);     //生成对象1

	cout << endl;
	cout << "Point p1:";
	p1.print();
	cout << endl;
	Point p2(x * 2, y * 2); //生成点对象2

	cout << "Point p2: ";
	p2.print();
	cout << endl;

	p1.moveRight(10);
	cout << "After moving right, p1: ";
	p1.print();
	cout << endl;

	p2.moveDown(-10); // 位移量为负,即向上移动

	cout << "After moving down, p2: ";
	p2.print();
	cout << endl;
	return 0;
}

等待网络加载图片···