侯捷C++(String类)

注意事项(class with pointer members)#

Big Three,三个特殊函数:析构函数、拷贝构造函数、拷贝赋值函数。

代码(String类)#

#include <iostream>
#include <bits/c++config.h>
#include <string.h>
using namespace std;

class String
{
public:
    //构造函数,只有构造函数可以用列表初始化
    inline String(const char* cStr = " ") : m_data(new char[strlen(cStr) + 1])
    {
        strcpy(m_data, cStr);
    }
    //拷贝构造函数
    inline String(const String& otherStr) : m_data(new char[strlen(otherStr.m_data) + 1])
    {
        strcpy(m_data, otherStr.m_data);
    }
    //析构函数
    inline ~String()
    {
        delete []m_data;
    }
    //追加函数
    String& append(const String& otherStr);

    //得到m_data
    inline char* getChar() const { return m_data; }
    //拷贝赋值函数
    String& operator = (const String& otherStr);
private:
    char* m_data;
};

inline String& String::append(const String& otherStr)
{
    char *pTmp = new char[strlen(this->m_data) + strlen(otherStr.m_data) +1];
    strcpy(pTmp, this->m_data);
    strcat(pTmp, otherStr.m_data);
    m_data = pTmp;
    return *this;
}

inline String& String::operator = (const String& otherStr)
{
    //检测自我赋值,否则会删除自己
    if (this == &otherStr)
    {
        return *this;
    }
    else
    {
        delete []m_data;
        m_data = new char[strlen(otherStr.m_data) + 1];
        strcpy(m_data, otherStr.m_data);
        return *this;
    }
}

inline ostream& operator << (ostream& os, const String& str)
{
    return os << str.getChar() << endl;
}

int main()
{
    String s1("hello");
    cout << "构造函数:" << s1;
    String s2(s1);
    cout << "拷贝构造函数:" << s2;
    String s3 = s2;
    cout << "拷贝赋值函数:" << s3;
    String s4;
    s4.append("hello").append(" world!");
    cout << "append函数:" << s4;
    return 0;
}

posted @   小森林呐  阅读(68)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
点击右上角即可分享
微信分享提示
主题色彩