目录
1.mystring.h
2.mystring.cpp
3.mian.cpp
4.运行结果
1.mystring.h
#ifndef MYSTRING_H
#define MYSTRING_H
#include <cstring>
class MyString
{
private:
char* str; // 保存C风格字符串地址
int len; // 保存字符串的实际长度
public:
// 无参构造函数
MyString() : len(32){ // 给定默认初始大小
str = new char[len]; // 堆区申请空间
strcpy(str, ""); // 字符串赋空值
}
// 有参构造函数
MyString(const char* s){
len = strlen(s); // 计算外部字符串大小,不包含\0
str = new char[len + 1]; // 堆区申请对应大小空间
strcpy(str, s); // 拷贝字符串
}
// 析构函数
~MyString(){
delete str; // 释放指针成员属性指向的堆空间
}
// 拷贝函数
MyString(MyString &other) : len(other.len){
str = new char[len + 1]; // 堆区申请对应大小空间
strcpy(str, other.str); // 拷贝字符串
}
// 字符串判空函数
bool empty();
// 计算字符串实际长度函数
int size();
// 返回C风格字符串
char* &c_str();
// at函数
char &at(int sub);
};
#endif // MYSTRING_H
2.mystring.cpp
#include "mystring.h"
bool MyString::empty(){
return strlen(this->str) ? false : true;
}
int MyString::size(){
return strlen(this->str);
}
char* &MyString::c_str(){
return this->str;
}
char &MyString::at(int sub){
return this->str[sub];
}
3.mian.cpp
#include <iostream>
#include "mystring.h"
using namespace std;
int main()
{
// 有参构造函数
MyString s1("hello");
cout << "s1 = " << s1.c_str() << endl;
// 拷贝构造函数
MyString s2(s1);
cout << "s2 = " << s2.c_str() << endl;
// 判空
if(s2.empty()){
cout << "s2空" << endl;
} else {
cout << "s2非空" << endl;
}
// 计算大小
cout << "s2大小= " << s2.size() << endl;
// at函数
s2.at(0) = 'H';
cout << "s2 = " << s2.c_str() << endl;
return 0;
}
4.运行结果