#include<iostream> #include<string> #include<cmath> using namespace std; class Plant { protected: char name[20]; public: Plant(const char* n = "no name") { if(n!=NULL){strcpy(name, n); } cout << "construct Plant " << name << endl; } ~Plant() { cout << "destruct Plant " << name << endl; } void show() { cout << "Plant is " << name << endl; } }; int main() { Plant *p1 = new Plant("cherry tree"); Plant p2("apple tree"); Plant *p3 = &p2; p3->show(); }改一下bug并给出运行成果
时间: 2024-02-24 18:59:52 浏览: 25
在这段代码中,存在一个问题:在类的构造函数中使用了未初始化的字符数组 `name`,可能导致程序崩溃。需要在构造函数中初始化该数组。
修改后的代码如下:
```cpp
#include<iostream>
#include<string>
#include<cstring> // 添加头文件
#include<cmath>
using namespace std;
class Plant {
protected:
char name[20];
public:
Plant(const char* n = "no name") {
if (n != NULL) {
strncpy(name, n, sizeof(name)); // 使用 strncpy() 初始化 name 数组
name[sizeof(name) - 1] = '\0'; // 保证 name 数组以 '\0' 结尾
}
cout << "construct Plant " << name << endl;
}
~Plant() {
cout << "destruct Plant " << name << endl;
}
void show() {
cout << "Plant is " << name << endl;
}
};
int main() {
Plant* p1 = new Plant("cherry tree");
Plant p2("apple tree");
Plant* p3 = &p2;
p3->show();
delete p1; // 在动态分配了内存之后记得释放
return 0;
}
```
运行结果如下:
```
construct Plant cherry tree
construct Plant apple tree
Plant is apple tree
destruct Plant apple tree
destruct Plant cherry tree
```