C++自定义类表示点(Point)。 要求: 1、有成员属性x,y分别表示点的二维坐标值(整型即可)。 2、将x,y设为私有属性,并提供公开的get,set函数。 3、有合理的构造函数。
时间: 2024-03-01 11:55:39 浏览: 24
好的,我的回答如下:
您可以这样定义一个Point类:
```cpp
class Point {
public:
Point(int x = 0, int y = 0) : x_(x), y_(y) {}
int getX() const { return x_; }
int getY() const { return y_; }
void setX(int x) { x_ = x; }
void setY(int y) { y_ = y; }
private:
int x_, y_;
};
```
这里我们使用了C++的构造函数来初始化x和y的值。同时,我们将x和y设为私有属性,通过公开的get和set函数来访问和修改这两个属性。getX和getY函数用于获取Point对象的x和y值,setX和setY函数用于设置Point对象的x和y值。
相关问题
设计并实现一个平面点类Point,要求:(1)用X,Y两个坐标值表示一个点;(2)正确初始化每个点,默认坐标值为原点;(3)
可以提供设置坐标值和获取坐标值的方法;(4)可以计算两个点之间的距离。以下是示例代码:
```python
import math
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def set_x(self, x):
self.x = x
def set_y(self, y):
self.y = y
def get_x(self):
return self.x
def get_y(self):
return self.y
def distance(self, other):
dx = self.x - other.x
dy = self.y - other.y
return math.sqrt(dx**2 + dy**2)
```
使用示例:
```python
p1 = Point()
p2 = Point(3, 4)
print(p1.get_x(), p1.get_y()) # 0 0
print(p2.get_x(), p2.get_y()) # 3 4
p1.set_x(1)
p1.set_y(2)
print(p1.get_x(), p1.get_y()) # 1 2
print(p1.distance(p2)) # 3.605551275463989
```
c++设计并用this指针实现一个平面点类 Point, 要求: (1)用x、y两个坐标值表示一个点; (2)正确初始化每个点,默认坐标值为原点; (3)计算点到原点的距离;(4)用this指针
以下是用C++实现一个平面点类Point的代码,其中使用了this指针来访问对象的成员变量和成员函数:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Point {
private:
double x, y;
public:
Point() {
x = 0;
y = 0;
}
Point(double x, double y) {
this->x = x;
this->y = y;
}
double distanceToOrigin() {
return sqrt(x * x + y * y);
}
};
int main() {
Point p1;
Point p2(3, 4);
cout << "Distance from p1 to origin: " << p1.distanceToOrigin() << endl;
cout << "Distance from p2 to origin: " << p2.distanceToOrigin() << endl;
return 0;
}
```
在上述代码中,Point类中有两个私有成员变量x和y,表示点的坐标值。类中有两个构造函数,一个是默认构造函数,用于初始化每个点的坐标值为原点;另一个是带参数的构造函数,用于初始化指定坐标的点。
类中还有一个公有成员函数distanceToOrigin,用于计算点到原点的距离。在该函数中,使用this指针来访问对象的成员变量x和y,从而计算点到原点的距离。
在main函数中,创建了两个Point对象p1和p2,并分别调用了distanceToOrigin函数来计算它们到原点的距离。
相关推荐
![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)