概述
目录
实验代码
String.h
String.cpp
main.cpp主函数
实验总结
测试代码
主要任务:
创建一个String来进行以下测试
int main()
{
String s1("help!"), s2("Good!"), s3(s2), s4, s5;
cout << "s1=" << s1 << endl;//s1=help!
s3 = "help!";
cout << "s3=" << s3 << endl;//s3=help!
s3 = s2;
cout << "s3=" << s3 << endl;//s3=Good!
s3 += s2;
cout << "s3=" << s3 << endl;//s3=Good!Good!
cin >> s4;//输入jobs
cout << "s4=" << s4 << endl;//s4=jobs
s5 = s3+s4;
cout << "s5=" << s5 << endl;//s5=Good!Good!jobs
s5 = 'g';
cout << "s5=" << s5 << endl;//s5=g
cout << "strlen(s5)=" << s5.Length() << endl;//strlen(s5)=1
cout << boolalpha << (s3 == s1) << endl;//s3=Good!Good!和s1=help! 返回false
cout << boolalpha << (s3 < s1) << endl;//成立返回true
return 0;
}
实验代码
String.h
#pragma once
#include<iostream>
using namespace std;
class String
{
public:
friend ostream& operator<<(ostream& os, String& c);
friend istream& operator>>(istream& is, String& c);
String();
String(const char* s);
//复制构造
String(String& ss);
//移动构造函数
String(String&& s)noexcept;
//返回字符串长度
int Length();
//重载=,传入字符串
String& operator =(const char*c);
//重载=,深复制
String& operator =(String& c);
//重载= 移动构造
String& operator=(String&& c);
//重载= 传入单个字符
String& operator=(char c);
//重载+= 连接字符串
String& operator+=(String& c);
//重载+
String operator + (String & c);
//重载[]
char operator[](int i);
//重载==
bool operator==(String& c);
//重载<
bool operator<(String& c);
~String()
{
if (this->m_str != NULL)
{
delete m_str;
m_str = NULL;
}
}
private:
char* m_str;
int m_size;//含有的长度
};
String.cpp
#include"String.h"
String::String():m_size(0)
{
this->m_str = new char();
}
//有参构造
String::String(const char* s ): m_size(strlen(s))
{
this->m_str = new char[this->m_size+1];
//strcpy_s(m_str, m_size+1, s);
strcpy(m_str, s);
}
//复制构造
String::String(String& ss):m_size(ss.Length())
{
this->m_str = new char[m_size+1];
//strcpy_s(m_str, m_size+1, ss.m_str);
strcpy(m_str, ss.m_str);
}
//移动构造函数
String::String(String&& s)noexcept
{
this->m_size = s.m_size;
this->m_str = new char[this->m_size + 1];
strcpy(this->m_str, s.m_str);
}
//重载[]
char String::operator[](int i)
{
return this->m_str[i];
}
//重载==
bool String::operator==(String& c)
{
if (strcmp(this->m_str, c.m_str))//不相等时,返回非0,进入if
return false;
return true;
}
//重载<
bool String::operator<(String& c)
{
if (strcmp(this->m_str, c.m_str) < 0)
return true;
return false;
}
//赋值传入字符串
String& String::operator=(const char* c)
{
this->m_size = strlen(c);
this->m_str = new char[this->m_size + 1];
strcpy(this->m_str, c);
return *this;
}
//重载=,深复制
String& String::operator =(String& c)
{
this->m_size = c.Length();
this->m_str = new char[m_size+1];
strcpy(this->m_str, c.m_str);
return *this;
}
//重载= 移动构造
String& String::operator=(String&& c)
{
this->m_size = c.Length();
this->m_str = new char[m_size + 1];
strcpy(this->m_str, c.m_str);
return *this;
}
//重载= 传入单个字符
String& String::operator=(char c)
{
this->m_size = 1;
this->m_str = new char[2];
this->m_str[0] = c;
this->m_str[1] = '