string类编程实例

发布时间:2023年12月27日

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_str
	return 0;
}
文章来源:https://blog.csdn.net/qq_36091214/article/details/135231969
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。