实现基类Point类(X,Y坐标成员变量),定义有参构造函数,实现函数分别获取x,y坐标成员函数,实现display函数,定义一个point变量,输出当前点的坐标信息
时间: 2023-07-16 11:15:32 浏览: 54
以下是基类Point类的实现:
```c++
class Point {
protected:
double x;
double y;
public:
Point(double x, double y) : x(x), y(y) {}
double getX() const {
return x;
}
double getY() const {
return y;
}
void display() const {
std::cout << "Point (" << x << ", " << y << ")" << std::endl;
}
};
```
可以通过以下方式创建一个Point对象并输出当前点的坐标信息:
```c++
Point p(1.2, 3.4);
p.display(); // 输出:Point (1.2, 3.4)
```
相关问题
实现基类Point类(X,Y坐标成员变量),定义有参构造函数,实现函数分别获取x,y坐标成员函数,实现display函数,定义一个point变量,输出当前点的坐标信息。
好的,这是一个简单的基于C++的实现:
```c++
class Point {
private:
int x, y;
public:
Point(int x_, int y_): x(x_), y(y_) {} // 有参构造函数
int getX() const { return x; } // 获取x坐标
int getY() const { return y; } // 获取y坐标
void display() const { // 输出坐标信息
std::cout << "Current coordinates: (" << x << ", " << y << ")" << std::endl;
}
};
int main() {
Point p(1, 2); // 创建一个Point对象
p.display(); // 输出当前坐标信息
return 0;
}
```
输出结果:
```
Current coordinates: (1, 2)
```
以上代码中,我们首先定义了一个Point类,并在其中声明了x和y坐标成员变量。在有参构造函数中,我们给这两个变量赋值。getX和getY函数分别返回这两个坐标变量的值。display函数用于输出当前点的坐标信息。
在main函数中,我们创建了一个Point对象,并将x和y的值分别设置为1和2。接着,我们调用display函数输出当前点的信息。
运用c++定义一个Point类,派生出Rectangle和Circle类,计算个派生类对象的面积Area()。 要求:①Point类,Rectangle和Circle类都有成员变量、成员函数; ②分别写出他们的构造函数和析构函数; ③通过point的坐标计算面积。 ④在main函数中实现输出。
好的,我会尽力回答您的问题。下面是我实现的代码:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Point {
protected:
double x, y;
public:
Point(double x = 0, double y = 0) {
this->x = x;
this->y = y;
}
virtual ~Point() {}
double getX() const {
return x;
}
double getY() const {
return y;
}
};
class Rectangle : public Point {
private:
double width, height;
public:
Rectangle(double x = 0, double y = 0, double width = 0, double height = 0) : Point(x, y) {
this->width = width;
this->height = height;
}
~Rectangle() {}
double getWidth() const {
return width;
}
double getHeight() const {
return height;
}
double Area() const {
return width * height;
}
};
class Circle : public Point {
private:
double radius;
public:
Circle(double x = 0, double y = 0, double radius = 0) : Point(x, y) {
this->radius = radius;
}
~Circle() {}
double getRadius() const {
return radius;
}
double Area() const {
return M_PI * pow(radius, 2);
}
};
int main() {
Rectangle r(0, 0, 5, 3);
Circle c(0, 0, 2);
cout << "The area of the rectangle is: " << r.Area() << endl;
cout << "The area of the circle is: " << c.Area() << endl;
return 0;
}
```
在这个代码中,我们定义了一个Point类作为基类,然后派生出Rectangle和Circle类。在Rectangle和Circle类中,我们分别定义了它们的成员变量和成员函数,并且实现了Area()函数用于计算面积。在main函数中,我们创建了一个Rectangle对象和一个Circle对象,并输出它们的面积。
需要注意的是,我们在Point类中定义了虚析构函数,这是因为我们在Rectangle和Circle类中使用了多态性,如果不定义虚析构函数,可能会导致内存泄露。