实验三 C++ 面向对象初步 设计point类

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() {                                             //得到数据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 << "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;

}



  • 5
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值