c++ 类的组合

本文通过C++代码实现了一个二维坐标点类(Point)及线段类(Line),演示了类的构造过程,包括默认构造、拷贝构造,并计算两点间的距离。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <cmath>
using namespace std;

class Point{
	private:
		int x, y;
	
	public:
		Point(int a = 0, int b = 0)
		{
			x = a; y = b;
			cout << "Point construction: " << x << ", "<< y << endl;
		}
		Point(Point &p) // copy constructor,其实数据成员是int类型,默认也是一样的 
		{
			x = p.x;
			y = p.y;
			cout << "Point copy construction: " << x << ", "<< y << endl; 
		}
		int getX()
		{
			return x;
		}
		int getY()
		{
			return y;
		}
}; 

class Line{
	private:
		Point start, end;
	
	public:
		Line(Point pstart, Point pend):start(pstart), end(pend) // 组合类的构造函数对内前对象成员的初始化必须采用初始化列表形式
		{
			cout << "Line constructior " << endl;
		}
		float getDistance()
		{
			double x = double(end.getX()-start.getX());
			double y = double(end.getY()-start.getY());
			return (float)(sqrt)(x*x+y*y);
		}
};

int main()
{
	Point p1(10,20),p2(100,200);
	Line line(p1,p2);
	cout << "The distance is: "<<line.getDistance()<<endl; return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值