#include <bits/stdc++.h>
using namespace std;
class String
{
public:
String(const char *str = NULL);
String(const String &str); //拷贝构造
~String();
String &operator=(const String &str); //赋值运算符,返回引用
String operator+(const String &str) const;
String &operator+=(const String &str);
char &operator[](int n) const; //下标操作符
bool operator==(const String &str) const;
int size() const;
const char *c_str() const; //string转为char*
private:
char *data;
int length;
};
String::String(const char *str) //声明是用户可以看到的部分,客户非常信任地使用这个特性,
// 希望得到一定的结果,但是你在实现里使用了不同的缺省值,那么将是灾难性的。因此编译器禁止声明和定义时同时定义缺省参数值。
{
if (!str)
{
length = 0;
data = new char[1];
*data = '\0';
}
else
{
length = strlen(str);
data = new char[length + 1];
strcpy(data, str); //把str的末尾 \0 也拷贝过来
}
}
String::String(const String &str)
{
length = str.size();
data = new char[length + 1];
strcpy(data, str.c_str());
}
String &String::operator=(const String &str)
{
if (this == &str)
{
return *this;
}
length = str.size();
delete[] data;
//先把现有的data删除,需要重新分配内存
data = new char[length + 1];
strcpy(data, str.c_str());
return *this;
}
String &String::operator+=(const String &str)
{
length += str.size();
char *newdata = new char[length + 1];
strcpy(newdata, data);
strcat(newdata, str.c_str());
delete[] data; //把原先的字符数据释放
data = newdata;
return *this;
}
char &String::operator[](int n) const
{
if (n > length)
{
return data[length - 1]; //越界返回最后一个字符
}
return data[n];
}
String String::operator+(const String &str) const
{
String newstr;
newstr.length = this->length + str.size();
newstr.data = new char[newstr.length + 1];
strcpy(newstr.data, (*this).data);
strcat(newstr.data, str.data);
return newstr;
}
bool String::operator==(const String &str) const
{
if (length != str.size())
{
return false;
}
return strcmp(data, str.c_str()) ? false : true;
}
String::~String()
{
delete[] data;
length = 0;
}
const char *String::c_str() const //返回值是不可变的,这个暴露的接口用户无法修改数据
{
return data;
}
int String::size() const
{
return length;
}
int main()
{
char a[] = "Hello", b[] = "World!";
String s1(a), s2(b),s3("Hello"),s4(a);
cout << "s1赋值以后:" << endl;
cout << s1.c_str() << endl;
s1 += s2;
cout << "s1+=s2赋值以后:" << endl;
cout << s1.c_str() << endl;
cout<<"测试下标操作符[]:"<<endl;
cout << s1[3] << endl;
cout<<"s2和s3比较==:"<<endl;
cout<<s2.c_str()<<" "<<s3.c_str()<<endl;
cout<<(s2==s3)<<endl;
cout<<"s3和s4比较==:"<<endl;
cout<<s3.c_str()<<" "<<s4.c_str()<<endl;
cout<<(s3==s4)<<endl;
return 0;
}
?
|