您的位置:首页 > 游戏 > 手游 > C++Day3

C++Day3

2024/11/18 18:25:37 来源:https://blog.csdn.net/Artorias_Ch/article/details/141687704  浏览:    关键词:C++Day3

作业:仿照string类,实现myString
 

main.cpp
#include "mystring.h"int main()
{//调用无参构造myString s1;cout << "扩容前size = " << s1.get_size() << "  str1 = " << s1.cToString() << endl;//调用构造的二倍扩容函数s1.expand();cout << "扩容后size = " << s1.get_size() << "  str1 = " << s1.cToString() << endl;//调用有参构造myString s2("hello world");cout << "size = " << s2.get_size() << "  str2 = " << s2.cToString() << endl;//调用at函数cout << "第一个字符:" << s2.at(0) << endl;cout << "第二个字符:" << s2.at(1) << endl;cout << "第三个字符:" << s2.at(2) << endl;//调用有参构造myString s3("");cout << "size = " << s3.get_size() << "  str3 = " << s3.cToString() << endl;//调用empty函数//判断字符串s2是否为空if (s2.empty())cout << "s2字符串为空!" << endl;elsecout << "s2字符串不为空!" << endl;//判断字符串s3是否为空if (s3.empty())cout << "s3字符串为空!" << endl;elsecout << "s3字符串不为空!" << endl;s3 = s2;cout << "my_size = " << s3.get_size() << "  str3 = " << s3.cToString()<< endl;return 0;
}
mystring.cpp
#include "mystring.h"
//无参构造
myString ::myString():size(10)
{str = new char[size];    //构造出一个长度为10的字符串strcpy(str,"");cout<<"调用无参构造"<<endl;
}
//有参构造
myString ::myString(const char *s)             //有参构造     string  s("hello wirld");
{size=strlen(s);str= new char[size +1];strcpy(str,s);cout<<"调用有参构造"<<endl;
}//判空函数
bool myString :: empty()
{if(this->size==0){return 1;}else{return 0;}
}
//size函数
int myString ::get_size()
{return size;
}
//c_str函数
const char* myString ::cToString()
{return this->str;
}
//at函数
char &myString ::at(int index)
{if (index >= 0 && index < size){return str[index];  // 返回索引为 index 的元素的引用}else{// 处理索引越界的情况throw std::out_of_range("Index out of bounds");}}
//二倍扩容
void myString ::expand()
{char *temp;size*=2;temp=new char[size];strcpy(temp,str);delete [] str;str =temp;}
//定义析构函数
myString :: ~myString()
{delete[]str;cout<<"调用析构函数"<<endl;
}
mystring.h
#ifndef MYSTRING_H
#define MYSTRING_H
#include <iostream>
#include<cstring>
using namespace std;class myString
{private:char *str;          //记录c风格的字符串int size;            //记录字符串的实际长度public://无参构造myString();//有参构造myString(const char *s);              //有参构造     string  s("hello wirld");//判空函数bool empty();//size函数int get_size();//c_str函数const char* cToString();//at函数char & at(int index);//二倍扩容void expand();//定义析构函数~myString();
};#endif // MYSTRING_H

 

思维导图

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com