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,欢迎来访。

原文链接: https://www.cnblogs.com/colourso/p/12759886.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/343934

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午2:22
下一篇 2023年3月2日 上午2:22

相关推荐