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

C++ 字符串重载运算符

时间:2015-03-11 10:52:10      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

#include<iostream.h>
#include<string.h>
//using namespace std;
class Cstring
{
public:
	Cstring()
	{
		p = new char[1];
		*p = '\0';
	}
	Cstring(const char *t);
	Cstring(const Cstring &t);
	~Cstring()
	{
		delete[]p;
	}
	bool operator<(const Cstring &t)const;
	friend bool operator > (const Cstring &str1,const Cstring &str2);
	Cstring& operator=(const Cstring &t);
	Cstring operator+(const Cstring &t)const;
	bool operator==(const Cstring &t)const;
	char& operator[](int index);
	
	void Show()
	{
		cout<<p<<endl;
	}
private:
	char *p;
};

Cstring::Cstring(const char *t)
{
	if(t == NULL)
		t = "";
	int n = strlen(t);
	p = new char[n+1];
	strcpy(p,t);
}
Cstring::Cstring(const Cstring &t)
{
	p = new char[strlen(t.p)+1];
	strcpy(p,t.p);
}
bool Cstring::operator <(const Cstring &t)const
{
	if(strcmp(p, t.p) < 0)  
		return true;                                                
	else return false;
}
bool operator > (const Cstring &str1, const Cstring &str2)
{
	if(strcmp(str1.p, str2.p) > 0)  
		return true;                                                
	else return false;
}
bool Cstring::operator ==(const Cstring &t)const
{
	return strcmp(p,t.p) == 0;
}
char& Cstring::operator [](int index)
{
	return p[index];
}
Cstring Cstring::operator +(const Cstring &t)const
{
	char *pt;
	pt = new char[strlen(p)+strlen(t.p)+1];
	strcpy(pt,p);
	strcat(pt,t.p);
	Cstring temp(pt);
	delete[]pt;
	return temp;
}
Cstring& Cstring::operator =(const Cstring &t)
{
	if(this == &t)
		return *this;
	delete[]p;
	p = new char[strlen(t.p)+1];
	strcpy(p,t.p);
	return *this;
}

void main()
{
	Cstring s1("Hello");
	Cstring s2("World");
	Cstring s3;
	s1.Show();
// 	if(s1[0]>='A' &&s1[0]<='Z')
// 		s1[0] = s1[0]+32;
// 	s1.Show();
	cout <<(s1>s2)<<endl;
	cout <<(s1<s2)<<endl;
	s3 = s1;
	s3.Show();
	s3 = s1+s2;
	s3.Show();
}


在VC6.0下如果将头文件改为:

#include<iostream>
#include<string.h>
using namespace std;

就会出现下列错误

error C2248: ‘p‘ : cannot access private member declared in class ‘Cstring‘

C++ 字符串重载运算符

标签:

原文地址:http://blog.csdn.net/syytem004/article/details/44195155

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