设有如下代码,代码无法正常运行。请添加必要的成员函数使之能够正确运行。 #include <iostream> #include <string> using namespace std; class T { char *p1; public: T(char *s1=""); ~T(); void print() {cout<<"p1="<<p1<<endl;} }; T::T(char *s1) { p1=new char[strlen(s1)+1]; strcpy(p1,s1); } T::~T(){ delete [] p1;} int main() { T t1("Lucky boy"),t2(t1),t3; t1.print(); t2.print(); t3=t2=T("Welcome"); t2.print(); t3.print(); }
时间: 2024-01-03 21:03:49 浏览: 62
代码中缺少赋值运算符重载函数,需要添加以下成员函数:
```
T& operator=(const T& t) {
if (this == &t) return *this;
delete [] p1;
p1 = new char[strlen(t.p1)+1];
strcpy(p1, t.p1);
return *this;
}
```
完整代码如下:
```cpp
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class T {
char *p1;
public:
T(char *s1="");
~T();
T& operator=(const T& t) {
if (this == &t) return *this;
delete [] p1;
p1 = new char[strlen(t.p1)+1];
strcpy(p1, t.p1);
return *this;
}
void print() {cout<<"p1="<<p1<<endl;}
};
T::T(char *s1) {
p1=new char[strlen(s1)+1];
strcpy(p1,s1);
}
T::~T(){
delete [] p1;
}
int main() {
T t1("Lucky boy"),t2(t1),t3;
t1.print();
t2.print();
t3=t2=T("Welcome");
t2.print();
t3.print();
return 0;
}
```
阅读全文