c++通过派生点类创建线类
时间: 2024-02-01 22:13:07 浏览: 40
在C++中,可以通过派生子类来创建线类。具体步骤如下:
1. 创建点类
```c++
class Point {
private:
double x;
double y;
public:
Point(double x, double y) {
this->x = x;
this->y = y;
}
double getX() const {
return x;
}
double getY() const {
return y;
}
};
```
2. 创建线类
```c++
class Line {
public:
virtual double getLength() const = 0;
};
class LineByTwoPoints : public Line {
private:
const Point& p1;
const Point& p2;
public:
LineByTwoPoints(const Point& p1, const Point& p2) : p1(p1), p2(p2) {}
virtual double getLength() const {
double dx = p1.getX() - p2.getX();
double dy = p1.getY() - p2.getY();
return sqrt(dx * dx + dy * dy);
}
};
```
在上述代码中,我们定义了一个抽象的线类 `Line`,并实现了一个具体的线类 `LineByTwoPoints`,该类通过两个点来确定一条直线,并重写了 `getLength` 方法来计算线段长度。
3. 测试
```c++
int main() {
Point p1(0, 0);
Point p2(3, 4);
LineByTwoPoints line(p1, p2);
std::cout << "The length of the line is " << line.getLength() << std::endl;
return 0;
}
```
输出结果:
```
The length of the line is 5
```
在测试代码中,我们实例化了两个点 `p1` 和 `p2`,用它们来创建一条线段 `line`,并调用 `getLength` 方法来计算线段长度。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)