码迷,mamicode.com
首页 > 编程语言 > 详细

实现C++ String类

时间:2015-09-13 19:46:45      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

头文件,函数大都隐式内联了。

#ifndef MYSTRING_H
#define MYSTRING_H

#include <iostream>
#include <string.h>

class MyString {
	friend std::ostream& operator<<(std::ostream &, const MyString &);
	friend std::istream& operator>>(std::istream &, MyString &);
public:
	MyString() : content(new char[1]) { *content = ‘\0‘; }
	MyString(const char *str) : content(new char[strlen(str) + 1]) 
	{
		strcpy_s(content, strlen(content), str);
	}
	//MyString(const size_t sz, char &c);

	MyString(const MyString &ms) : content(new char[ms.size() + 1]) { strcpy_s(content, strlen(content), ms.content); }

	MyString& operator=(const MyString &);
	~MyString() { delete[] content; }

	void swap(MyString &rhs)
	{
		std::swap(content, rhs.content);
	}
	size_t size() const { return strlen(content); }

	const char& operator[](std::size_t n) const
	{
		if(n < strlen(content))
			return content[n];
	}
	
	bool operator==(const MyString &rhs)
	{
		return strcmp(content, rhs.content);
	}

	bool operator!=(const MyString &rhs)
	{
		return strcmp(content, rhs.content);
	}

	MyString operator+=(const MyString &rhs);	

	MyString operator+(const MyString &rhs)
	{
		*this += rhs;
		return *this;
	}
private:
	char *content;
};

#endif

  myString.cpp

#include "myString.h"

MyString & MyString::operator=(const MyString &ms)
{
	char *temp = ms.content;
	delete ms.content;
	content = temp;

	return *this;
}

MyString MyString::operator+=(const MyString &rhs)
{
	if (rhs.content == nullptr)
		return *this;

	if (this == &rhs) {
		MyString copy(*this);
		return *this += copy; 
	}

	char *content_old = content;
	content = new char[strlen(content) + strlen(rhs.content) + 1];
	strcpy_s(content, strlen(content), content_old);
	strcat_s(content, strlen(content), rhs.content);
	delete[] content_old;
	return *this;
}

std::ostream& operator<<(std::ostream &os, const MyString &ms)
{
	os << ms.content << std::endl;
	return os;
}

std::istream& operator>>(std::istream &is, MyString &ms)
{
	is >> ms.content;
	return is;
}

  main函数测试

#include <iostream>
#include "myString.h"

using std::cout; using std::cin; using std::endl;

int
main()
{
	MyString str1;
	cout << "Enter a string" << endl;
	cin >> str1;
	cout << str1 << endl;

	MyString str2("test");
	cout << str2 << endl;
	cout << str2[2] << endl;

	return 0;
}

  

 

实现C++ String类

标签:

原文地址:http://www.cnblogs.com/fanjinhua/p/4805335.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!