我们要实现string类,首先必须了解string类都有哪些操作?
从C++原生string类中我们可以知道:
1. string类的定义和初始化:
string s1; //默认初始化,s1是一个空字符串
string s2=s1; //s2是s1的副本
string s3="hello";
string s4(10,'c'); //s4内容是cccccccccc
实现代码:
class MyString{
public:
MyString(const char* newStr=""):str(new char[strlen(newStr)+1]){
strcpy(str,newStr);
}
MyString(const MyString& other):str(newchar[strlen(other.str)+1]){
strcpy(str, other.str);
}
//拷贝构造函数引用传值的目的是避免拷贝构造函数无限制的递归下去
MyString(const int len, const char c) :str(new char[len + 1]) { //s4的实现
for (int i = 0; i < len; i++)str[i] = c;
str[len] = '\0';
}
~MyString(){
delete[] str;
}
private:
char* _str;
};
拷贝构造函数为什么使用引用传递?详见:拷贝构造函数的参数类型必须是引用
对于为什么使用“:”初始化成员变量: C++构造函数初始化列表与构造函数中的赋值的区别
2. string对象的操作
os<<s;
is>>s;
s.size();
s.empty();
s[n]
s1+s2;
s1==s2;
s1!=s2;
还有<,>,<=,>=等操作
代码实现:
实现<<操作符
ostream& operator << (ostream& os,MyString &myStr){
os<<myStr.str;
return os;
}
实现>>操作符
istream& operator >> (istream& is,MyString &myStr){
myStr.str=new char[1024*2];
is>>myStr.str;
return is;
}
实现+运算符
MyString operator + (MyString& myStr1,MyString &myStr2) {
MyString newStr;
size_t len = strlen(myStr1.str) + strlen(myStr2.str);
newStr.str = new char[len + 1];
strcpy(newStr.str, myStr1.str);
strcat(newStr.str, myStr2.str);
newStr.str[len] = '\0';
return newStr;
}
实现=操作符
MyString& MyString::operator =(MyString &myStr) {
if (myStr.str != NULL) {
delete[] str;
str = new char[strlen(myStr.str) + 1];
strcpy(str, myStr.str);
str[strlen(myStr.str)] = '\0';
}
return *this;
}
实现==操作符
bool operator == (const MyString &myStr1,const MyString &myStr2)
{
return strcmp(myStr1.str, myStr2.str) ? false : true;
}
实现!=操作符
bool operator !=(const MyString&myStr1, const MyString &myStr2) {
return strcmp(myStr1.str, myStr2.str) ? true : false;
}
还有很多操作符就不一一实现了
在main函数中测试代码如下:
int main() {
MyString string1,string2="world"; //string1为空字符串
cin >> string1 >> string2;
if (string1 == string2) { cout << "yes"<<endl; }
if (string1 != string2) { cout << "no"<<endl; }
MyString string3(string2);
cout << string1<<endl;
cout << string2 << endl;
cout << string3 << endl;
cout << string1 + string2 << endl;
system("pause");
return 0;
}