1.定义circle类 2.在main中定义circle对象数组 3.在main中定义circle对象指针,指向已有的对象 4.在main中定义circle对象指针,使用new和delete分配和释放内存
时间: 2024-05-11 09:18:06 浏览: 61
1. 定义Circle类
```
class Circle {
private:
double radius;
public:
Circle(double r) {
radius = r;
}
double area() {
return 3.14 * radius * radius;
}
};
```
2. 在main中定义Circle对象数组
```
int main() {
Circle circles[3] = { Circle(1.0), Circle(2.0), Circle(3.0) };
for(int i = 0; i < 3; i++) {
cout << "Circle " << i+1 << " area: " << circles[i].area() << endl;
}
return 0;
}
```
3. 在main中定义Circle对象指针,指向已有的对象
```
int main() {
Circle c1(4.0);
Circle *p = &c1;
cout << "Circle area using pointer: " << p->area() << endl;
return 0;
}
```
4. 在main中定义Circle对象指针,使用new和delete分配和释放内存
```
int main() {
Circle *p = new Circle(5.0);
cout << "Circle area using dynamic allocation: " << p->area() << endl;
delete p;
return 0;
}
```
阅读全文