C++设计一个折线类 CLine 1、该类有属性: 组成线的点数、点坐标数组(动态或静态)、线的颜色(整数)、线的宽度(整数); 2、该类有方法: a) 设置和获取颜色 两个方法 b) 设置和获取线宽 两个方法 c) 添加一个点到线上 b) 在线上删除一个点 e) 修改一个线上点的坐标 f) 获取线上的点数 g) 获取一个线上点的坐标
时间: 2023-06-14 09:05:48 浏览: 183
C++折线类的实现代码
以下为C++代码示例:
```cpp
#include <iostream>
#include <vector>
using namespace std;
class CLine {
private:
int pointNum; // 点的数量
vector<pair<int, int>> points; // 点坐标数组
int color; // 线的颜色
int lineWidth; // 线的宽度
public:
// 构造函数
CLine() : pointNum(0), color(0), lineWidth(0) {}
// 设置和获取颜色
void setColor(int c) { color = c; }
int getColor() const { return color; }
// 设置和获取线宽
void setLineWidth(int w) { lineWidth = w; }
int getLineWidth() const { return lineWidth; }
// 添加一个点到线上
void addPoint(int x, int y) {
points.push_back(make_pair(x, y));
pointNum++;
}
// 在线上删除一个点
void deletePoint(int index) {
if (index < 0 || index >= pointNum) return;
points.erase(points.begin() + index);
pointNum--;
}
// 修改一个线上点的坐标
void modifyPoint(int index, int x, int y) {
if (index < 0 || index >= pointNum) return;
points[index] = make_pair(x, y);
}
// 获取线上的点数
int getPointNum() const { return pointNum; }
// 获取一个线上点的坐标
pair<int, int> getPoint(int index) const {
if (index < 0 || index >= pointNum) return make_pair(0, 0);
return points[index];
}
};
```
使用示例:
```cpp
int main() {
CLine line1;
line1.setColor(1);
line1.setLineWidth(2);
line1.addPoint(0, 0);
line1.addPoint(1, 1);
line1.addPoint(2, 3);
line1.addPoint(4, 2);
cout << "Line1 color: " << line1.getColor() << endl;
cout << "Line1 width: " << line1.getLineWidth() << endl;
cout << "Line1 point num: " << line1.getPointNum() << endl;
for (int i = 0; i < line1.getPointNum(); i++) {
pair<int, int> point = line1.getPoint(i);
cout << "Point " << i << ": (" << point.first << ", " << point.second << ")" << endl;
}
line1.deletePoint(1);
line1.modifyPoint(2, 5, 4);
cout << "After delete and modify:" << endl;
cout << "Line1 point num: " << line1.getPointNum() << endl;
for (int i = 0; i < line1.getPointNum(); i++) {
pair<int, int> point = line1.getPoint(i);
cout << "Point " << i << ": (" << point.first << ", " << point.second << ")" << endl;
}
return 0;
}
```
阅读全文