- #include
- #include
-
- using namespace std;
-
- class myString
- {
- private:
- char *str; //记录c风格的字符串
- int size; //记录字符串的实际长度
- public:
-
- //无参构造
- myString():size(10)
- {
- str = new char[size]; //构造出一个长度为10的字符串
- strcpy(str,""); //赋值为空串
- }
-
- //有参构造
- myString(const char *s) //string s("hello world")
- {
- size = strlen(s)+1;
- str = new char[size];
- strcpy(str, s);
- }
-
- //拷贝构造
- myString(char *s,int i):str(new char(*s)),size(i){
- strcpy(this->str,s);
- this->size = i;
- cout<<"拷贝构造函数"<
- }
-
- //析构函数
- ~myString(){
- delete str;
- }
-
- //拷贝赋值函数
- myString &operator = (const myString &other){
- if(&other != this){
- this->str = new char[size];
- memset(str,0,size);
- strcpy(str,other.str);
- }
- return *this;
- }
-
- //判空函数
- bool empty(){
- if(strlen(str) == 0)
- return false;
- else
- return true;
- }
-
- //size函数
- int mysize(){
- return size;
- }
-
- //c_str函数
- const char* c_str(){
- return str;
- }
-
- //at函数
- char &at(int pos){
- if(pos>=size || pos<0){
- cout<<"访问越界"<
- }
- return str[pos];
- }
-
- //加号运算符重载
- const myString operator+(const myString &s)const{
- myString m;
- strcpy(m.str,this->str);
- strcat(m.str,s.str);
- m.size = strlen(m.str);
- return m;
- }
-
- //加等于运算符重载
- const myString operator+=(const myString &s){
- strcat(this->str,s.str);
- this->size = strlen(this->str);
- return *this;
- }
-
- //关系运算符重载(>)
- bool operator >(const myString &s)const{
- if(this->size < s.size){
- return false;
- }
- else{
- for(int i=0;i<this->size;i++){
- if(*(this->str+i)<*(s.str+i)){
- return false;
- }
- }
- }
- return true;
- }
-
- //中括号运算符重载
- char & operator[](const int pos)const{
- if(pos>=size || pos<0){
- cout<<"访问越界"<
- }
- return *(str+pos);
- }
- };
-
-
- int main(){
-
- //展示字符串
- myString s1("ssssyyyy");
- myString s2("wwwwhhhh");
- cout<
c_str()<<" "<c_str()< -
- //重载加法运算符
- myString s3;
- cout<
mysize()< - s3=s1+s2;
- cout<
c_str()< -
- //at运算
- cout<
at(3)< -
- //加等于
- s3+=s1;
- cout<
c_str()< - cout<
mysize()< -
- //关系运算
- if(s3>s1){
- cout<<"s3>s1"<
- }
- else
- cout<<"s3
< -
- //中括号
- cout<
3]<<" "<6]<< " "<8]< -
-
-
- return 0;
- }

-
相关阅读:
[AIGC] 使用Google的Guava库中的Lists工具类:常见用法详解
Linux第一个小程序——进度条
nginx负载均衡和高可用
CSS 常用样式background背景属性
【CNN-SVM回归预测】基于CNN-SVM实现数据回归预测附matlab代码
毫无基础的人如何入门 Python ?
使用Visual Studio Code 进行Python编程(一)
Linux下的Docker安装,以Ubuntu为例
说一下 JVM 有哪些垃圾回收器?
Python 使用PIL读取图像自动旋转exif信息
-
原文地址:https://blog.csdn.net/2301_77665369/article/details/133521398