优化这段代码并消除bug:#include<iostream> #include<string> using namespace std; class Vehicle{ protected: string name; string color; public: Vehicle(string n,string c):name(n),color(c){}; virtual void display(); }; class Car : public Vehicle{ private: int pas; public: Car(string n,string c,int p):Vehicle(n,c),pas(p){}; void display(){ cout << name << " " << color << " " << pas << endl; }; }; class Truck : public Vehicle{ private: double weight; public: Truck(string n,string c,double d):Vehicle(n,c),weight(d){}; void display(){ cout << name << " " << color << " " << weight << endl; }; }; int main() { Vehicle *p; char type; char name[110],color[110]; int pas; double cap; while(cin>>type) { cin>>name>>color; if(type == 'C') { cin>>pas; Car car(name,color,pas); p = &car; p->display(); } else if(type == 'T') { cin>>cap; Truck truck(name,color,cap); p = &truck; p->display(); } } return 0; }
时间: 2024-01-07 18:04:19 浏览: 83
优化后的代码如下,主要是将类的成员变量改为指针类型,避免在栈上分配内存导致指针失效:
```cpp
#include<iostream>
#include<string>
using namespace std;
class Vehicle{
protected:
string name;
string color;
public:
Vehicle(string n, string c): name(n), color(c){};
virtual void display() = 0;
virtual ~Vehicle(){} // 添加虚析构函数
};
class Car : public Vehicle{
private:
int *pas; // 改为指针类型
public:
Car(string n, string c, int p): Vehicle(n, c){
pas = new int(p); // 动态分配内存
};
void display(){
cout << name << " " << color << " " << *pas << endl;
};
~Car(){ // 添加析构函数,释放内存
delete pas;
}
};
class Truck : public Vehicle{
private:
double *weight; // 改为指针类型
public:
Truck(string n, string c, double d): Vehicle(n, c){
weight = new double(d); // 动态分配内存
};
void display(){
cout << name << " " << color << " " << *weight << endl;
};
~Truck(){ // 添加析构函数,释放内存
delete weight;
}
};
int main() {
Vehicle *p;
char type;
char name[110], color[110];
int pas;
double cap;
while(cin>>type) {
cin>>name>>color;
if(type == 'C') {
cin>>pas;
p = new Car(name, color, pas); // 动态分配内存
p->display();
delete p; // 释放内存
}
else if(type == 'T') {
cin>>cap;
p = new Truck(name, color, cap); // 动态分配内存
p->display();
delete p; // 释放内存
}
}
return 0;
}
```
此外,还需要添加虚析构函数,在子类析构时能够自动调用父类析构函数,释放父类的内存。并且在动态分配内存后需要在适当的时候释放内存,避免内存泄漏。
阅读全文