阅读背景:

MyString的简单实现

来源:互联网 

 MyString.h 文件

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

class MyString
{
public:
	/*默认的无参和cons char *参数的构造函数;
	*如果不想允许MyString str="abc"类型的赋值,可将其声明为explicit
	*/
	MyString(const char* str=""); 

	//复制构造函数
	MyString(const MyString& other);
	
	/*重载赋值操作符,
	*返回值为自身的引用是为了支持连续赋值,如str1 = str2 =str3;
	*返回值为const是为了禁止(str1=str2)=str3这样的等式
	*/
	const MyString& operator=(const MyString& other);
	const MyString& operator=(const char* str);
		 
	bool operator!() const;  //重载!操作符, const函数内不会改变类的数据成员
	
	/* 重载[]操作符
	*重载此操作符后可以使用下标访问对象元素,拥有和字符串数组相同的功能
	*传入的值必须是无符号整数,返回一个char 引用是为了允许MyString str("abc"); str[0]='c';这样的赋值操作
	*/
	char& operator[](unsigned int index);
	/*
	*如果不想允许上面的赋值,可以返回const型,这样就只能读取了; 此外函数定义为const含有一个好处:可以被const对象访问;
	*char ch =str[0];// 合法
	*str[0]=ch; //非法
	*/
	const char& operator[](unsigned int index) const;  

	/*重载+操作符,连接两个字符串
	*为什么不把该重载函数设为类成员函数? 如果将+重载为成员函数,则左操作数必须为MyString类型
	*同时,由于MyString有隐式类型转换构造函数,这里的两个参数可以使MyString类型的也可以是const char * 或者char *
	*由语义可知,返回值不应为引用;
	* 定义为友元是因为该函数需要访问类的私有成员,且该函数职位该类使用
	*/
	friend MyString operator+(const MyString& s1, const MyString& s2);
/*重载+=操作符
* 这里可以声明为类成员函数,因为左操作数肯定是MyString类型;
*/
	MyString& operator+=(const MyString& other);
	
	//声明为友元函数是因为,不能再ostream内重载<< >> 操作符,返回引用是为了支持连续输出或输入
	friend ostream& operator<<(ostream& os, const MyString& str);
	friend istream& operator>>(istream& is, MyString& str);
	~MyString(void);

	void Display() const;
	unsigned int length(){
		return strlen(str_);
	}
private:
	MyString& Assign(const char* str);
	char* AllocAndCpy(const char* str);
	char* str_;
};

#endif // _STRING_H_
#ifndef _STRING_H_
#define



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: