设计一个三维流线类 CPline,定义点类 CPt3d ,有3个成员 x,y,z; 1、该类有属性:点坐标数组,点数; 2、该类有方法: a) 在线末尾添加一个点的函数 AppendPt b) 重载运算符 [] ,实现:设置和获取线上某点信息。 c) 重载运算符 = ,实现线的复制赋值; d) 将函数 AppendPt 重载为 + 运算。
时间: 2023-06-13 22:08:46 浏览: 202
下面是实现 CPt3d 类和 CPline 类的代码:
```cpp
#include <iostream>
#include <vector>
class CPt3d {
public:
CPt3d(double x = 0, double y = 0, double z = 0) : x_(x), y_(y), z_(z) {}
double x() const { return x_; }
double y() const { return y_; }
double z() const { return z_; }
private:
double x_, y_, z_;
};
class CPline {
public:
CPline() : pts_(), n_(0) {}
void AppendPt(const CPt3d& pt) {
pts_.push_back(pt);
++n_;
}
CPt3d& operator[](int i) { return pts_[i]; }
const CPt3d& operator[](int i) const { return pts_[i]; }
CPline& operator=(const CPline& other) {
pts_ = other.pts_;
n_ = other.n_;
return *this;
}
CPline operator+(const CPt3d& pt) const {
CPline new_line(*this);
new_line.AppendPt(pt);
return new_line;
}
int n() const { return n_; }
private:
std::vector<CPt3d> pts_;
int n_;
};
int main() {
CPline line;
line.AppendPt(CPt3d(0, 0, 0));
line.AppendPt(CPt3d(1, 0, 0));
line.AppendPt(CPt3d(1, 1, 0));
line.AppendPt(CPt3d(0, 1, 0));
line.AppendPt(CPt3d(0, 1, 1));
std::cout << "Line points:" << std::endl;
for (int i = 0; i < line.n(); ++i) {
std::cout << "(" << line[i].x() << "," << line[i].y() << "," << line[i].z() << ")" << std::endl;
}
CPline new_line = line + CPt3d(0, 0, 1);
std::cout << "New line points:" << std::endl;
for (int i = 0; i < new_line.n(); ++i) {
std::cout << "(" << new_line[i].x() << "," << new_line[i].y() << "," << new_line[i].z() << ")" << std::endl;
}
return 0;
}
```
运行结果如下:
```
Line points:
(0,0,0)
(1,0,0)
(1,1,0)
(0,1,0)
(0,1,1)
New line points:
(0,0,0)
(1,0,0)
(1,1,0)
(0,1,0)
(0,1,1)
(0,0,1)
```
阅读全文