题目:自制string类实现部分功能
代码:
main.cpp
#include <iostream>
#include<cstring>
#include<cstdlib>
#include<text1h.h>
using namespace std;
int main()
{
my_string a1;
my_string a2("hello");
my_string a3="world";
my_string a4(3,'q');
a1="nihao";
cout<<a1.c_str()<<endl;
a1=a2;
cout<<a1.c_str()<<endl;
cout<<a2.c_str()<<endl;
cout<<a3.c_str()<<endl;
cout<<a4.c_str()<<endl;
cout<<"a2.length="<<a2.length()<<endl;
if(a3.empty())
{
cout<<"空"<<endl;
}
else
{
cout<<"非空"<<endl;
}
cout<<"a3[0]="<<a3.at(0)<<" a3[1]="<<a3.at(1)<<endl;
return 0;
}
text1.cpp
#include<text1h.h>
#include<iostream>
char *my_string::c_str()
{
return data;
}
int my_string::length()
{
return strlen(data);
}
bool my_string::empty()
{
return strlen(data)==0?1:0;
}
char my_string::at(int n)
{
return data[n];
}
text1.h
#ifndef TEXT1H_H
#define TEXT1H_H
#include <iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
class my_string
{
private:
char *data;
int size;
public:
my_string():size(15)
{
data=new char[size];
data[0]='\0';
}
my_string(const char* str):size(15)
{
data=new char[size];
strcpy(data,str);
}
my_string(int n,char str):size(15)
{
data=new char[size];
for(int i=0;i<n;i++)
{
data[i]=str;
}
data[n]='\0';
}
my_string(const my_string &other):size(other.size)
{
strcpy(data,other.data);
}
my_string & operator=(const my_string & other)
{
this->size=other.size;
strcpy(data,other.data);
return *this;
}
~my_string()
{
delete [] data;
data=nullptr;
}
char *c_str();
int length();
bool empty();
char at(int n);
};
#endif // TEXT1H_H
运行结果:
