实现string类是一道考验c++基础知识的好题,接下来看这样一道题目,顺便了解string类的内部实现
已知string类的原型代码如下,请编写l类string的7个函数:
#ifndef STRING_H
#define STRING_H
#include<iostream>
using namespace std;
class String {
public:
String(const char *str = nullptr);//普通构造函数
String(const String &str);//拷贝构造函数
~String();//析构函数
String & operator=(const String &other);//赋值构造函数
String operator+(const String &other);//连接函数
bool operator==(const String &other);//判断相等
int getlength();//返回长度
friend ostream & operator<<(ostream &out, const String &str);//重载输出运算符
private:
char *m_data;
};
#endif // !STRING_H
具体实现:由于我实在VS2017中测试的,因此在vs2017中strcpy、strcat不安全,改为了strcpy_s、strcat_s,区别主要在于后者指定长度,避免溢出造成异常。
#include"String.h"
#include<cstring>
String::String(const char *str) {
if (str == nullptr)
{
m_data = new char[1];
m_data = '\0';
}
else {
int len = strlen(str);
m_data = new char[len+1];
//strcpy(m_data, str);
strcpy_s(m_data, len + 1, str);
}
}
String::~String() {
if (m_data) {
delete[] m_data;
m_data = nullptr;
}
}
String::String(const String &str) {
if (!str.m_data) {
m_data = new char[1];
m_data = '\0';
}
else {
int len = strlen(str.m_data);
m_data = new char[len + 1];
//strcpy_s(m_data, str.m_data)
strcpy_s(m_data, len + 1, str.m_data);
}
}
String &String::operator=(const String &other) {
if (this != &other) {
delete[] m_data;
if (!other.m_data) {
m_data = 0;
}
else {
int len = strlen(other.m_data);
m_data = new char[len + 1];
//strcpy_s(m_data, other.m_data);
strcpy_s(m_data, len + 1, other.m_data);
}
}
return *this;
}
String String::operator+(const String &other) {
String newString;
if (!m_data) {
newString = other;
}
else if (!other.m_data) {
newString = *this;
}
else {
newString.m_data = new char[strlen(m_data) + strlen(other.m_data) + 1];
//strcpy_s(newString.m_data, m_data);
strcpy_s(newString.m_data, strlen(m_data) + strlen(other.m_data) + 1,m_data);
//strcat(newString.m_data, other.m_data);
strcat_s(newString.m_data, strlen(m_data) + strlen(other.m_data) + 1, other.m_data);
}
return newString;
}
bool String::operator==(const String &other) {
if (strlen(m_data) != strlen(other.m_data))
return false;
else {
return strcmp(m_data, other.m_data) ? false : true;
}
}
int String::getlength() {
return strlen(m_data);
}
ostream & operator<<(ostream & out, const String &str) {
out << str.m_data;
return out;
}
例子:
#include"String.h"
#include<iostream>
using namespace std;
int main() {
String s;
const char *p = "12345";
String s1(p);
s = s1;
if (s == s1)
cout << "Yes" << endl;
else
cout << "No" << endl;
cout << s << endl;
String s2(s + s1);
cout << s2.getlength() << endl;
cout << s2 << endl;
}