实现一个名叫SimpleCiecle的简单圆类。其数据成员int *itsRadius为一个指向其半径值的指针,存放其半径值。设计对数据成员的各种操作,给出这个类的完整实现并测试这个类。
时间: 2024-05-13 17:21:15 浏览: 12
好的,我明白了。以下是SimpleCircle的完整实现:
```
class SimpleCircle {
public:
SimpleCircle() : itsRadius(new int(0)) {}
SimpleCircle(int radius) : itsRadius(new int(radius)) {}
SimpleCircle(const SimpleCircle& other) : itsRadius(new int(*other.itsRadius)) {}
~SimpleCircle() { delete itsRadius; }
int getRadius() const { return *itsRadius; }
void setRadius(int radius) { *itsRadius = radius; }
SimpleCircle& operator=(const SimpleCircle& other) {
if (this != &other) {
delete itsRadius;
itsRadius = new int(*other.itsRadius);
}
return *this;
}
private:
int* itsRadius;
};
```
这个类定义了一个半径值,用指针存储并动态分配内存,以确保对象被复制或销毁时内存安全。它还提供了一些简单的方法来访问和修改半径值。
以下是一个简单的测试程序,用于创建SimpleCircle对象并进行操作:
```
#include <iostream>
using namespace std;
int main() {
SimpleCircle circle(5);
cout << "The radius of the circle is " << circle.getRadius() << endl;
circle.setRadius(10);
cout << "The radius of the circle is now " << circle.getRadius() << endl;
SimpleCircle otherCircle;
otherCircle = circle;
cout << "The radius of the other circle is " << otherCircle.getRadius() << endl;
return 0;
}
```
当运行时,这个程序应该输出以下内容:
```
The radius of the circle is 5
The radius of the circle is now 10
The radius of the other circle is 10
```
希望这个SimpleCircle类能够满足您的需求!
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)