![]() |
#2
某一天2017-05-05 17:10
如下代码,很多地方并不合理,可能会有bug,或者跟实际需求有偏差,仅供参考:
#pragma once #include <list> // 点类 class SPoint { public: double m_dX; // x坐标 double m_dY; // y坐标 void Move(const SPoint& rPoint) { m_dX += rPoint.m_dX; m_dY += rPoint.m_dY; } }; // 多边形类 class CPolygon { public: CPolygon() { } ~CPolygon() { Clear(); } // 清空所有点 void Clear() { for (std::list<SPoint*>::const_iterator it = m_listPoint.begin(); it != m_listPoint.end(); ++it) { delete *it; } m_listPoint.clear(); } // 插入点 void InsertPoint(const SPoint& rPoint) { SPoint* pPoint = new SPoint(rPoint); m_listPoint.push_back(pPoint); } // 删除某个点 todo:查找要删除的点时效率太低,顶点少的话影响不大 bool RemovePoint(const SPoint& rPoint) { for (std::list<SPoint*>::iterator it = m_listPoint.begin(); it != m_listPoint.end(); ++it) { if ((rPoint.m_dX == (*it)->m_dX) && (rPoint.m_dY == (*it)->m_dY)) // todo:这个比较可能有问题 { delete *it; m_listPoint.erase(it); return true; } } return false; } // 移动 水平和垂直移动距离由rPoint确定 void Move(const SPoint& rPoint) { for (std::list<SPoint*>::iterator it = m_listPoint.begin(); it != m_listPoint.end(); ++it) { (**it).Move(rPoint); } } // 读取顶点列表 std::list<SPoint*> GetPoints() const { return m_listPoint; } private: std::list<SPoint*> m_listPoint; // 顶点坐标集合 }; [此贴子已经被作者于2017-5-5 17:11编辑过] |
(1)多边形的顶点也封装为类,包含x和y坐标,用构造函数进行初始化,用Move成员函数进行位置移动,根据需要设计其他成员函数;
(2)多边形通过构造函数进行初始化,顶点个数由参数传递,然后动态创建顶点对象,顶点不要用固定长度的数组保存;
(3)在多边形的析构函数中删除和释放顶点对象;
(4)在多边形类中设置Move成员函数,实现位置的整体移动,并输出各个顶点的新位置;
(5)为多边形类设计InsertPoint和RemovePoint成员函数,动态增加或删除顶点,并输出更改后的顶点列表;
(6)设计main函数和测试数据验证上述功能,可以尝试在网上查阅C++的画线函数,实现多边形的图形化输出。
这是题目要求
新手上路,恳请各路大神帮忙!求类与对象的源代码