用C加加编写声明一个点类Point,包含了坐标x,y属性.定义构造函数,成员函数getX()得到x,getY()得到y,求出该点到原点的距离.在主函数中定义Point类对象并输出其到原点的距离
时间: 2024-05-13 18:21:01 浏览: 47
```cpp
#include <iostream>
#include <cmath>
using namespace std;
class Point {
private:
double x, y;
public:
Point(double x, double y) {
this->x = x;
this->y = y;
}
double getX() {
return x;
}
double getY() {
return y;
}
double distanceToOrigin() {
return sqrt(x * x + y * y);
}
};
int main() {
Point p(3, 4);
cout << "The distance from point (" << p.getX() << ", " << p.getY() << ") to origin is " << p.distanceToOrigin() << endl;
return 0;
}
```
相关问题
用c++编写点类point的数据成员包括坐标x、坐标y,成员函数包括构造函数,返回坐标x的函数getx()和返回坐标y的函数gety()
以下是用 C++ 编写的 `point` 类的示例代码:
```cpp
class point {
private:
double x, y;
public:
// 构造函数
point(double x = 0, double y = 0) : x(x), y(y) {}
// 返回坐标 x 的函数
double getx() const {
return x;
}
// 返回坐标 y 的函数
double gety() const {
return y;
}
};
```
在这个类中,我们使用了私有变量 `x` 和 `y` 来存储点的坐标,使用了公有成员函数 `getx()` 和 `gety()` 来分别返回点的 x 坐标和 y 坐标。同时,我们使用了默认参数来定义构造函数,使得创建 `point` 对象时可以不必传入初始坐标值。
点类point的数据成员包括坐标x、坐标y,成员函数包括构造函数,返回坐标x的函数getx()和返回坐标y的函数gety()
下面是一个简单的 C++ 实现:
```c++
class Point {
private:
double x, y;
public:
Point(double x, double y) {
this->x = x;
this->y = y;
}
double getx() const {
return x;
}
double gety() const {
return y;
}
};
```
在这个实现中,我们定义了一个 `Point` 类,并包含了两个私有成员变量 `x` 和 `y` 分别表示点的横坐标和纵坐标。构造函数 `Point` 用于初始化这两个变量,而 `getx` 和 `gety` 函数则分别返回点的横坐标和纵坐标。注意,这里使用了 `const` 关键字来表示这两个函数不会修改 `x` 和 `y` 的值。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)