#ifndef String_hpp
#define String_hpp
#include <stdio.h>
#include <iostream>
using namespace std;
class String
{
friend bool operator==(const String&, const String&);
friend String operator+(const String&, const String&);
friend bool operator<(const String&, const String&);
public:
String()
{
len=0;
rep=new char[len+1];
}
String(const char*);
String(const String&);
~ String()
{
if (rep) {
delete rep;
rep=NULL;
}
}
const String& operator=(const String&);
const String& operator+=(const String&);
const char at(int index) const; // 如果越界要抛出异常
char at(int index); // 如果越界要抛出异常
const char& operator[](int index) const;
char& operator[](int index);
int length();
friend ostream& operator<<(ostream&out,String& a)
{
out<<a.rep;
return out;
}
private:
char* rep; // 存放字符串
int len; // 字符串的长度
};
#endif /* String_hpp */
#include "String.hpp"
#include <assert.h>
bool operator==(const String&a, const String&b)
{
bool yes = false;
if (strcmp(a.rep, b.rep)==0) {
yes = true;
}
return yes;
}
String operator+(const String&a, const String&b)
{
int len = a.len+b.len;
char* temp = new char[len+1];
for (int i =0; i<a.len; i++) {
temp[i] = a.rep[i];
}
for (int i = 0; i<b.len; i++) {
temp[i+a.len] = b.rep[i];
}
// 或
// strcpy(temp,a.rep);
// strcat(temp,b.rep);
String str(temp);
delete temp;
return str;
}
bool operator<(const String&a, const String&b)
{
bool yes = false;
if (strcmp(a.rep, b.rep)<0)
{
yes = true;
}
return yes;
}
String:: String(const char*a)
{
if (a) {
len = (int)strlen(a);
rep = new char[len+1];
strcpy(rep, a);
}
else
{
len = 0;
rep = new char[1];
strcpy(rep, "");
}
}
String:: String(const String&a)
{
len = a.len;
rep = new char[a.len+1];
strcpy(this->rep, a.rep);
}
const String&String::operator=(const String&a)
{
if (this!=&a) {
this->len = a.len;
delete this->rep;
rep = new char[len+1];
strcpy(this->rep, a.rep);
}
return *this;
}
const String&String:: operator+=(const String&a)
{
this->len+=a.len;
char* temp =this->rep;
this->rep = new char[len+1];
strcpy(this->rep,temp);
strcat(this->rep,a.rep);
delete temp;
return *this;
}
const char String::at(int index) const // 如果越界要抛出异常
{
一、Assert简介
作用:是用于对程序进行调试的,对于执行结构的判断,而不是对于业务流程的判断。(相当于一个if ()语句,如果满足断言的执行程序,就继续执行程序,如果不满足则抛错误)
assert(index>=0&&index<len);
return rep[index];
}
char String::at(int index) // 如果越界要抛出异常
{
assert(index>=0&&index<len);
return rep[index];
}
const char& String::operator[](int index) const
{
return rep[index];
}
char& String::operator[](int index)
{
return rep[index];
}
int String::length()
{
return len;
}