栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

实现c++中的String类

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

实现c++中的String类

在本文中我们自己将自己定义并测试c++中的string类。

实现代码如下:

#pragma once
//String.h
#include
using namespace std;
#pragma warning(disable:4996)
class String {
private:
	char* str;
	int size;
public:
	String();
	String(const char* p);
	String(String& p);
	~String();
	int Length();
	String& operator=(const String& p);
	String operator+(const String& p);
	String& operator+=(const String& p);
	char& operator[](int i);
	bool operator==(const String& p);
	bool operator<(const String& p);
	String operator=(const char* p);
	friend ostream& operator<<(ostream& out,String& p);
	friend istream& operator>>(istream& in,String& p);
};
String::String() {
	size = 0;
	str = new char[1];
	str[0] = '';
}
String::String(const char* p) {
	size = strlen(p);
	str = new char[size + 1];
	strcpy_s(str,size+1, p);
}
String::String(String& p) {
	size = p.size;
	str = new char[size + 1];
	strcpy_s(str, size+1, p.str);
}
String::~String() {
	if (str != NULL) {
		delete[] str;
		str = NULL;
		size = 0;
	}

}
int String::Length() {
	return size;
}
String String::operator+(const String& p)
{
	String a;
	a.size = size + p.size;
	delete[]a.str;
	a.str = new char[a.size + 1];
	memset(a.str, 0, a.size);
	strcat_s(a.str, size+1, str);
	cout << a << endl;
	strcat_s(a.str,a.size+1, p.str);
	cout << a << endl;
	cout << a << endl;
	return a;
}
String& String::operator+=(const String& p) {
	*this = *this + p;
	return *this;
}
char& String::operator[](int i) {
	if (i >= size)
	{
		cout << "索引超过最大值" << endl;
		return str[0];
	}
	return str[i];
}
bool String::operator==(const String& p) {
	return !strcmp(str, p.str);
}
bool String::operator<(const String& p) {
	if (size < p.size)return true;
	else return false;
}
String String::operator=(const char* p) {
	size = strlen(p);
	str = new char[size + 1];
	strcpy_s(str, size + 1, p);
	return *this;
}
ostream& operator<<(ostream& out,String& p) {
	out << p.str;
	return out;
}
istream& operator>>(istream& in, String& p) {
	in >> p.str;
	const char* tem = p.str;
	p.size = strlen(tem);
	p.str = new char[p.size + 1];
	strcpy(p.str, tem);
	return in;
}
String& String::operator=(const String& p)
{
	if (this != &p) 
	{
		size = p.size;
		str = new char[size + 1];
		strcpy(str, p.str);
	}
	return *this;
}

测试代码如下:

#include"String.h"
int main() {
	String s1("Help!"), s2("Good!"), s3(s2), s4, s5;
	cout << "s1=" << s1 <
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/832998.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号