CompositePattern.cppRUN

#include <iostream>

//以下类中,凡不修改成员变量的函数(非构造/析构函数)都修饰成const函数

class Vector2D
{
private:
	double x, y;

public:
	Vector2D()
	{
		x = y = 0;
	}

	Vector2D(double x, double y)
	{
		this->x = x;
		this->y = y;
	}

	double Magnitude()const
	{
		return sqrt((*this) * (*this));
	}

	double operator*(const Vector2D& v)const
	{
		return x * v.x + y * v.y;
	}

	Vector2D operator+(const Vector2D& v)const
	{
		return Vector2D(x + v.x, y + v.y);
	}

	Vector2D operator-(const Vector2D& v)const
	{
		return Vector2D(x - v.x, y - v.y);
	}
};


class Line2D
{
private:
	Vector2D v1, v2;

public:
	Line2D() {}
	Line2D(const Vector2D& first, const Vector2D& second) : v1(first), v2(second)
	{
	}

	double Length()const
	{
		Vector2D v = v1 - v2;
		return v.Magnitude();
	}
};


void Test()
{
	Vector2D v1(1.0, 1.0), v2(2.0, 2.0), v3 = v2 - v1;
	
	Line2D line(v1, v2);
	double len = line.Length();
}


int main()
{
	Test();
	return 0;
}