指出代码错误并修改#include<iostream> using namespace std; #include<cstring> class Teacher { public: Teacher() { } Teacher(char *p,int a) { pname=new char[strlen(p)+1]; strcpy(pname,p); age=a; } Teacher(Teacher &t) { pname=new char[strlen(t.pname)+1]; strcpy(pname,t.pname); age=t.age; } Teacher& operator =(Teacher &t) { delete []pname; pname=new char[strlen(t.pname)+1]; strcpy(pname,t.pname); age=t.age; return *this; } ~Teacher() { delete []pname; } void Disp() { cout<<"Teacher:"<<pname<<","<<age<<endl; } private: char *pname; //存名字的地址 int age; }; class Student { public: Student() { } Student(char *n,int s) { strcpy(name,n); score=s; } void Disp() { cout<<"Student:"<<name<<","<<score<<endl; } protected: char name[10]; int score; }; class Tutor { public: Tutor() { } Tutor(char *n1,int s,char *n2,int a):s(n1,s),t(n2,a) { num=0; } Tutor(Tutor &t):s(t.s),t(t.t) { num=t.num; } void Date() { num++; } void Disp() { s.Disp(); t.Disp(); cout<<"Num:"<<num<<endl; } protected: Student s; Teacher t; int num;//存储师生会面次数 }; int main() { char name1[15],name2[15]; int score,age; cin>>name1>>score>>name2>>age; Tutor tt1(name1,score,name2,age),tt2; tt1.Disp(); tt1.Date(); //师生碰面一次 tt2=tt1; //此处调用的哪段代码? tt2.Disp(); Tutor tt3=tt1; //此处调用的哪段代码? tt3.Date(); tt3.Disp(); return 0; }
时间: 2024-01-17 22:06:09 浏览: 56
代码错误已经指出并修改,如下:
```c++
#include<iostream>
#include<cstring>
using namespace std;
class Teacher {
public:
Teacher() {
pname = NULL;
age = 0;
}
Teacher(char *p, int a) {
pname = new char[strlen(p) + 1];
strcpy(pname, p);
age = a;
}
Teacher(Teacher &t) {
pname = new char[strlen(t.pname) + 1];
strcpy(pname, t.pname);
age = t.age;
}
Teacher& operator =(Teacher &t) {
if (this != &t) {
delete[] pname;
pname = new char[strlen(t.pname) + 1];
strcpy(pname, t.pname);
age = t.age;
}
return *this;
}
~Teacher() {
delete[] pname;
}
void Disp() {
cout << "Teacher:" << pname << "," << age << endl;
}
private:
char *pname; //存名字的地址
int age;
};
class Student {
public:
Student() {
name[0] = '\0';
score = 0;
}
Student(char *n, int s) {
strcpy(name, n);
score = s;
}
void Disp() {
cout << "Student:" << name << "," << score << endl;
}
protected:
char name[10];
int score;
};
class Tutor {
public:
Tutor() {
num = 0;
}
Tutor(char *n1, int s, char *n2, int a) :s(n1, s), t(n2, a) {
num = 0;
}
Tutor(Tutor &t) :s(t.s), t(t.t) {
num = t.num;
}
void Date() {
num++;
}
void Disp() {
s.Disp();
t.Disp();
cout << "Num:" << num << endl;
}
protected:
Student s;
Teacher t;
int num;//存储师生会面次数
};
int main() {
char name1[15], name2[15];
int score, age;
cin >> name1 >> score >> name2 >> age;
Tutor tt1(name1, score, name2, age), tt2;
tt1.Disp();
tt1.Date(); //师生碰面一次
tt2 = tt1; //调用的是Tutor类的默认拷贝赋值函数
tt2.Disp();
Tutor tt3 = tt1; //调用的是Tutor类的拷贝构造函数
tt3.Date();
tt3.Disp();
return 0;
}
```
需要注意的是,构造函数和析构函数中要对类中动态分配的内存进行管理和释放,拷贝构造函数和拷贝赋值函数中要进行深拷贝操作,保证不同对象之间的数据互不影响。此外,在main函数中,对象的拷贝构造和拷贝赋值调用时需要特别注意。
阅读全文