自定义类似string的类(有以下不完整的类信息,请完善构造函数、析构函数、复制构造函数、输出函数等) class Mystring { private: char *text; public: Mystring(char *ch); //构造函数 //请完善 };
时间: 2024-02-20 17:57:04 浏览: 32
以下是完善后的类信息:
```c++
#include <iostream>
#include <cstring>
using namespace std;
class Mystring {
private:
char *text;
public:
Mystring(char *ch); //构造函数
Mystring(const Mystring &str); //复制构造函数
~Mystring(); //析构函数
void print(); //输出函数
};
Mystring::Mystring(char *ch) {
int len = strlen(ch);
text = new char[len + 1];
strcpy(text, ch);
}
Mystring::Mystring(const Mystring &str) {
int len = strlen(str.text);
text = new char[len + 1];
strcpy(text, str.text);
}
Mystring::~Mystring() {
delete[] text;
}
void Mystring::print() {
cout << text << endl;
}
```
上述代码中,构造函数中通过传入的char*类型指针来初始化text成员变量,复制构造函数中通过另一个Mystring类型对象来初始化text成员变量,析构函数中释放text指向的内存,输出函数中用于输出text成员变量的值。需要注意的是,在使用完text指向的内存后,需要将其释放,否则可能会造成内存泄漏。