#include <iostream> #include <string> using namespace std; class Person {static int f; protected: string name_; public: Person(){cout<<"A person without name is created."<<endl;f=0;} Person(string name):name_(name){cout<<"Person "<<name_<<" is created."<<endl;f=1;} virtual ~Person(){ if(f==1) cout<<"Person "<<name_<<" is erased."<<endl; if(f==0) cout<<"A person without name is erased."<<endl; } }; Person::static int f=0; class Teacher:virtual public Person { protected: string pos_; public: Teacher(string name,string pos):Person(name),pos_(pos){cout<<"Teacher "<<name_<<" "<<pos_<<" is created."<<endl;} ~Teacher(){cout<<"Teacher "<<name_<<" is erased."<<endl;} }; class Student:virtual public Person { protected: double sco_; public: Student(string name,double sco):Person(name),sco_(sco){cout<<"Student "<<name_<<" "<<sco_<<" is created."<<endl;} ~Student(){cout<<"Student "<<name_<<" is erased."<<endl;} }; int main(){ string name,pos; double sco; cin>>name>>pos>>sco; Person person; Person *p; p=new Teacher(name,pos); delete p; Person *q; q=new Student(name,sco); delete q; return 0; }哪错了?
时间: 2024-03-26 10:39:25 浏览: 76
这段代码有几个错误:
1. `Person::static int f=0;` 应该改为 `int Person::f=0;`,静态成员变量的定义需要在类外进行。
2. `Person person;` 这个对象没有给出名字,也没有传递参数,因此构造函数会使用默认构造函数,输出的信息不符合要求。
3. `Person *p; p=new Teacher(name,pos); delete p;` 这段代码会导致内存泄漏,因为使用 new 动态分配了内存,但是没有使用 delete 进行释放,应该在 delete 之前加上 `delete p; p= nullptr;`。
4. `Person *q; q=new Student(name,sco); delete q;` 同样会导致内存泄漏,应该在 delete 之前加上 `delete q; q = nullptr;`。
修改后的代码如下:
```
#include <iostream>
#include <string>
using namespace std;
class Person {
static int f;
protected:
string name_;
public:
Person(): f(0) {
cout << "A person without name is created." << endl;
}
Person(string name): name_(name), f(1) {
cout << "Person " << name_ << " is created." << endl;
}
virtual ~Person() {
if (f == 1)
cout << "Person " << name_ << " is erased." << endl;
if (f == 0)
cout << "A person without name is erased." << endl;
}
};
int Person::f = 0;
class Teacher: virtual public Person {
protected:
string pos_;
public:
Teacher(string name, string pos): Person(name), pos_(pos) {
cout << "Teacher " << name_ << " " << pos_ << " is created." << endl;
}
~Teacher() {
cout << "Teacher " << name_ << " is erased." << endl;
}
};
class Student: virtual public Person {
protected:
double sco_;
public:
Student(string name, double sco): Person(name), sco_(sco) {
cout << "Student " << name_ << " " << sco_ << " is created." << endl;
}
~Student() {
cout << "Student " << name_ << " is erased." << endl;
}
};
int main() {
string name, pos;
double sco;
cin >> name >> pos >> sco;
Person person("Tom");
Person *p;
p = new Teacher(name, pos);
delete p; p = nullptr;
Person *q;
q = new Student(name, sco);
delete q; q = nullptr;
return 0;
}
```
阅读全文