- 2.9 string类编程实例
2.9 string类编程实例
实现一个字符串类String,为其提供可接受C风格字符串的析构函数、构造函数、拷贝构造函数和拷贝赋值函数
#include <iostream>
#include <cstring>
using namespace std;class String{
public:explicit String (const char *str){ //类型转换构造函数cout << "String(const char *)" << endl;this->str = new char[strlen(str)+1]; //+1 因为还要存'\0'strcpy(this->str, str);}String (const String &that) { //拷贝构造函数cout << "String(const String &)" << endl;this->str = new char[strlen(that.str) + 1];strcpy(this->str, that.str);}String &operator = (const String &that){ //拷贝赋值构造函数cout << "String &operator(const String &)" << endl;if(this != &that) {delete [] str;str = new char[strlen(that.str) + 1];strcpy(str, that.str);}return *this;}const char *c_str(){return str;}~String(void) { //析构造函数delete str;}void print(void) {cout << str << endl;}
private:char *str;
};int main(void) {String s1 = String("hello"); //类型转换构造函数s1.print();String s2 = s1; //拷贝构造函数s2.print();String s3 = String("world"); //类型转换构造函数s2 = s3; //拷贝赋值s2.print();cout << s3.c_str() << endl; //string :: c_strreturn 0;
}