String的构造函数、析构函数和赋值函数的实现(C++)

/* 编写类String的构造函数(普通构造和拷贝构造)、析构函数和赋值函数 */
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

class String {
    
    
public:
	String(const char *str = nullptr);         
	String(const String& other);      
	String& operator=(const String& other);
	~String(void);                         
private:
	char *m_String;   
};

/* ctor */
String::String(const char *str) {
    
    
	if (str == nullptr) {
    
    
		m_String = new char[1];           
		*m_String = '\0';                   
	}
	else {
    
    
		m_String = new char[strlen(str) + 1];
		strcpy(m_String, str);
	}
}

/* copy ctor */
String::String(const String &other) {
    
    
	m_String = new char[strlen(other.m_String) + 1];  
	strcpy(m_String, other.m_String);               
}

/* copy assignment */
String& String::operator=(const String& other) {
    
    
	if (this == &other) {
    
                              
		return *this;
	}
	delete[] m_String;          
	m_String = new char[strlen(other.m_String) + 1];
	strcpy(m_String, other.m_String);
	return *this;
}

/* dtor */
String::~String() {
    
    
	if (m_String != nullptr) {
    
    
		delete[] m_String;              
	}
}

int main()
{
    
    
	String test1("hello");           
	String test2("world");           
	String test3(test1);              
	test3 = test2;

	return 0;
}

如有侵权,请联系删除,如有错误,欢迎大家指正,谢谢

猜你喜欢

转载自blog.csdn.net/xiao_ma_nong_last/article/details/105334892
今日推荐