String类的普通构造函数,拷贝构造函数,赋值运算符,析构函数,不等号运算符、[]、+、流运算符重载

#ifndef _STRING_H_
#define _STRING_H_
#include <iostream>
using namespace std;

class String
{
public:
	String(const char* str = "");
	String(const String& other);
	String& operator=(const String& other);
	String& operator=(const char* str);

	bool operator!() const;
	char& operator[](unsigned int index);
	const char& operator[](unsigned int index) const;

	friend String operator+(const String& s1, const String& s2);
	String& operator+=(const String& other);

	friend ostream& operator<<(ostream& os, const String& str);
	friend istream& operator>>(istream& is, String& str);
	~String(void);

	void Display() const;

private:
	String& Assign(const char* str);
	char* AllocAndCpy(const char* str);
	char* str_;
};

#endif // _STRING_H_


#pragma warning(disable:4996)
#include "String.h"
#include <string.h>
//#include <iostream>
//using namespace std;

String::String(const char* str)
{
	str_ = AllocAndCpy(str);
}

String::String(const String& other)
{
	str_ = AllocAndCpy(other.str_);
}

String& String::operator=(const String& other)
{
	if (this == &other)
		return *this;

	return Assign(other.str_);
}

String& String::operator=(const char* str)
{
	return Assign(str);
}

String& String::Assign(const char* str)
{
	delete[] str_;
	str_ = AllocAndCpy(str);
	return *this;
}

bool String::operator!() const
{
	return strlen(str_) != 0;
}

char& String::operator[](unsigned int index)
{
	//return str_[index];
	//non const 版本调用 const版本

	return const_cast<char&>(static_cast<const String&>(*this)[index]);
}

const char& String::operator[](unsigned int index) const
{
	return str_[index];
}

String::~String()
{
	delete[] str_;
}

char* String::AllocAndCpy(const char* str)
{
	int len = strlen(str) + 1;
	char* newstr = new char[len];
	memset(newstr, 0, len);
	strcpy(newstr, str);

	return newstr;
}

void String::Display() const
{
	cout << str_ << endl;
}

String operator+(const String& s1, const String& s2)
{
	//int len = strlen(s1.str_) + strlen(s2.str_) + 1;
	//char* newstr = new char[len];
	//memset(newstr, 0, len);
	//strcpy(newstr, s1.str_);
	//strcat(newstr, s2.str_);
	//
	//String tmp(newstr);
	//delete newstr;
	String str = s1;
	str += s2;
	return str;
}

String& String::operator+=(const String& other)
{
	int len = strlen(str_) + strlen(other.str_) + 1;
	char* newstr = new char[len];
	memset(newstr, 0, len);
	strcpy(newstr, str_);
	strcat(newstr, other.str_);

	delete[] str_;

	str_ = newstr;
	return *this;
}

ostream& operator<<(ostream& os, const String& str)
{
	os << str.str_;
	return os;
}

istream& operator>>(istream& is, String& str)
{
	char tmp[1024];
	cin >> tmp;
	str = tmp;
	return is;
}

猜你喜欢

转载自blog.csdn.net/qq_34793133/article/details/80940745