C++面向对象练习(二)—— string类型的简单实现(一)

概览:C++面向对象练习:string类型的构造、析构函数实现。

本文首发于我的个人博客www.colourso.top,欢迎来访。


代码全部运行于VS2019

博客后续会持续更新补充。

题目

已知 类String的原型为:

class String
{
public:
  String(const char *str = NULL);	// 普通构造函数
  String(const String &other);    	// 拷贝构造函数
  ~String(void);    					// 析构函数
  String & operate =(const String &other);// 赋值函数
private:
  char *m_data;// 用于保存字符串
};

请编写String的上述4个函数。

String::String(const char* str)
{
    cout << "默认构造函数" << endl;
    if (str == NULL)
        this->m_data = new char['\0'];
    else
    {
        int length = strlen(str);
        this->m_data = new char[length + 1];
        strcpy_s(this->m_data, length+1, str);
    }
}

String::String(const String& other)
{
    cout << "拷贝构造函数" << endl;
    int length = strlen(other.m_data);
    this->m_data = new char[length + 1];
    strcpy_s(this->m_data, length + 1, other.m_data);
}

String::~String()
{
    cout << "析构函数" << endl;
    delete[] m_data;
    m_data = nullptr;
}

String& String::operator=(const String& other)
{
    cout << "重载=赋值" << endl;
    if (this == &other) //检查自赋值
        return *this;

    if (this->m_data)   //释放原有的内存资源
        delete[] this->m_data;

    int length = strlen(other.m_data);
    this->m_data = new char[length + 1];
    strcpy_s(this->m_data, length + 1, other.m_data);
    return *this;
}

执行:

//为了测试额外添加的一个成员函数
void String::print()
{
    cout << this->m_data << endl;
}


int main()
{
    String a("hello");
    a.print();

    String b(a);
    b.print();

    String c;
    c = a;
    c.print();

    return 0;
}

执行结果

默认构造函数
hello
拷贝构造函数
hello
默认构造函数
重载=赋值
hello
析构函数
析构函数
析构函数
  • 当函数参数有默认值的时候,并且函数的声明与定义分开的时候,默认参数只能出现在其中的一个地方。参考链接·:C++函数默认参数
  • 使用strlen(const char* str)求得字符串长度是从头截至到\0结束字符,但是不包括\0
  • 而在给字符串开辟空间时要注意额外加上\0的空间!

参考链接:

C++笔试题 String类的实现

C++笔试题之String类的实现

本文首发于我的个人博客www.colourso.top,欢迎来访。

posted @ 2020-04-23 12:04  Colourso  阅读(226)  评论(0编辑  收藏  举报