网站建设思路/360优化大师官方网站
2.1 设计 Point 类
(1)问题描述计算机的显示屏的坐标系是这样的,左上角的坐标为(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;
};
*********************************************************************
(2)问题要求请实现以下函数声明,要求能得到如下图所示的运行结果。
(1)接受用户的输入,生成两个对象。
(2)打印这两个点。
(3)向右平移其中一个点后,打印该点。向下平移另一个点后,打印该点。
(3)主函数代码框架
void main() {
int x, y;
cout << "Please input a point: ";
cin >> x >> y;
Point p1(x,y); // 生成点对象1
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;
}
(4)运行结果示例
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() { //得到数据xreturn x;}int getY() { //得到数据yreturn 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); //生成对象1cout << "Point p1:";p1.print();cout << endl;Point p2(x * 2, y * 2); //生成点对象2cout << "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;}