#ifndef __LINE_H__
#define __LINE_H__
// 平面点类
class Point
{
public:
Point();
Point(int x, int y);
Point(const Point& other);
~Point();
Point& operator=(const Point& other);
int getX()const{return m_x;}
int getY()const{return m_y;}
private:
int m_x;
int m_y;
};
// 平面线类
class Line
{
public:
Line();
Line(const Point& pStart, const Point& pEnd);
~Line();
bool isOnLine(const Point& pt)const;
private:
Point m_start;
Point m_end;
};
#endif
// __LINE_H__
// end of line.h
#include "line.h"
#include <iostream>
Point::Point() : m_x(0), m_y(0)
{
std::cout << "Point : A original point" << std::endl;
}
Point::Point( int x, int y ) : m_x(x), m_y(y)
{
std::cout << "Point : " << x << "," << y << std::endl;
}
Point::Point( const Point& other ) : m_x(other.m_x), m_y(other.m_y)
{
std::cout << "Copy a point : " << m_x << "," << m_y << std::endl;
}
Point::~Point()
{
}
Point& Point::operator=( const Point& other )
{
m_x = other.m_x;
m_y = other.m_y;
return *this;
}
//////////////////////////////////////////////////////////////////////////
Line::Line()
{
std::cout << "Line : A original point" << std::endl;
}
Line::Line( const Point& pStart, const Point& pEnd )
{
m_start = pStart;
m_end = pEnd;
std::cout << "Line : Start(" << pStart.getX() << "," << pStart.getY() << ")" << '\t';
std::cout << "End(" << pEnd.getX() << "," << pEnd.getY() << ") " << std::endl;
}
Line::~Line()
{
}
bool Line::isOnLine( const Point& pt ) const
{
// (x1*y2-x2*y1)=(x1*y3-x3*y1)网摘算法
const int& x = pt.getX();
const int& y = pt.getY();
int t1 = m_start.getX() * m_end.getY();
t1 -= m_end.getX() * m_start.getY();
int t2 = m_start.getX() * y;
t2 -= x * m_start.getY();
if (t1 == t2) {
return true;
}
return false;
}
// end of line.cpp
主函数调用:
Point p1(2, 2);
Point p2(3, 3);
Point p3(4, 4);
Line l(p1, p2);
if (l.isOnLine(p3)) {
std::cout << "Is on the Line" << std::endl;
} else {
std::cout << "Not on the Line" << std::endl;
}
关于线上还是线下(相对平面而言),我就不写完了。楼主请再自行思考下。上面的代码只是参考,考虑并不全面。