怎么说呢。留个纪念,关于字符串的重载

等号重载的时候,一要记得先释放旧的内存!!!!!!!!!总忘记

MyString.h

#pragma once
#include<iostream>
using namespace std;
class MyString
{
public:
	MyString();

	MyString(char *p);
	MyString(const MyString &m1);

	~MyString();
	friend ostream &operator<<(ostream &out, MyString &t1);
	friend istream &operator>>(ostream &in, MyString &t2);
	MyString &operator=(MyString & t3);
	void printF();
	MyString &operator=(char * t3);
	char & MyString::operator[](int i);
	int operator>(MyString &t5);
public:
	char *p;
	int length;
};

  MyString.cpp

#include "MyString.h"
using namespace std;


MyString::MyString()
{
	length=0;
	this->p=new char [length +1];
}

MyString::MyString(char *p)
{
	if(this->p=NULL)
	{
		this->length=0;
		this->p=NULL;
	}
	else
	{
		this->length=strlen(p);
		this->p=new char [length +1];
		strcpy(this->p,p);
	}
}
//MyString::MyString(char *p)
//{
//	if (this->p == NULL)
//	{
//		length = 0;
//		this->p = new char[length + 1];
//		strcpy(this->p, "");
//	}
//	else
//	{
//		this->length = strlen(p);
//		this->p = new char[length + 1];
//		strcpy(this->p, p);
//	}
//}
MyString::MyString(const MyString &m1)
{
	this->length=m1.length;
	this->p=new char [length +1];
	strcpy(this->p,m1.p);
}
MyString::~MyString()
{
	if(p!=NULL)
	{
		length=0;
		delete [] p;
	}
}
void MyString::printF()
{
	cout<<this->p;
}


ostream & operator<<(ostream & out, MyString &t1)
{
	out<<t1.p;
	return out;
}
istream &operator>>(istream &in, MyString &t2)
{
	cin >> t2;//这句不理解啊
	return in;
}

//[] 的重载	cout<<a1<<endl;
//a[i]
char & MyString::operator[](int i)
{
	return this->p[i];
}
//等号的重载。a1=a2;a1=“sds”

MyString &MyString::operator=(MyString & t3)
{
		if(p!=NULL)
	{
		delete [] p;
		length=0;
	}
	if(p=NULL)
	{
		length=0;
		this->p=NULL;
	}
	else
	{
	this->length=t3.length;
	this->p=new char [length +1];
	strcpy(this->p,t3.p);
	}
	return *this;

}
//a1=“sds”
MyString &MyString::operator=(char * t4)
{
	if(p!=NULL)
	{
		delete [] p;
		length=0;
	}
	if(p=NULL)
	{
		length=0;
		this->p=NULL;
	}
	else
	{
		this->length=strlen(t4);
		this->p=new char[length +1];
		strcpy(p,t4);
	}
	return *this;
}

//a4>a1

int MyString::operator>(MyString &t5)
 {
	 return strcmp(t5.p,this->p);
 }

  main.cpp

#include<iostream>
#include"MyString.h"
using namespace std;
//构造函数要求
//MyString a;
//MyString a(“dddd”); 
//MyString b = a;
//
//常用的操作符
//<< >> != == > < =

//cout<<a1<<endl;


int main()
{
MyString a;
MyString a1("dddd");
//需要重载<<操作符
//[] 的重载	cout<<a1<<endl;

//MyString b=a;
/*for(int i=0;i<a1.length;i++)
{
cout<<a1[i]<<" ";
}
*/
MyString a4="fsfsdf";
a4[2]='2';
cout<<a4[2];
cout<<a4;

if(a4>a1)
{
cout<<"ok";
}

system("pause");


}

  

原文地址:https://www.cnblogs.com/xiaochige/p/6603357.html