You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现C++自定义String类的带空格自动拼接功能?

实现自定义String类的带空格自动拼接+运算符重载

针对你的需求,我们可以通过重载operator+实现字符串间自动添加空格的拼接,同时支持多字符串链式拼接(如s1 + s2 + s3)。下面是具体实现方案:

1. 自定义String类基础框架

先确保String类具备基础的内存管理能力(深拷贝、析构),避免浅拷贝问题,以下是简化的基础框架:

#include <cstring>
#include <iostream>

class String {
private:
    char* m_data;
    size_t m_length;

    // 辅助函数:分配内存并复制字符串
    void copyFrom(const char* str) {
        m_length = strlen(str);
        m_data = new char[m_length + 1];
        strcpy(m_data, str);
    }

public:
    // 构造函数
    String(const char* str = "") {
        copyFrom(str);
    }

    // 拷贝构造函数
    String(const String& other) {
        copyFrom(other.m_data);
    }

    // 析构函数
    ~String() {
        delete[] m_data;
    }

    // 赋值运算符重载
    String& operator=(const String& other) {
        if (this != &other) {
            delete[] m_data;
            copyFrom(other.m_data);
        }
        return *this;
    }

    // 获取字符串内容
    const char* c_str() const {
        return m_data;
    }

    // 获取字符串长度
    size_t length() const {
        return m_length;
    }
};

2. 重载operator+实现带空格拼接

为支持链式拼接,将operator+实现为非成员函数(确保左右操作数都能被正确处理),自动在两个字符串间添加空格,同时处理空字符串的边界情况(避免多余空格):

// 重载operator+:自动添加空格拼接两个字符串
String operator+(const String& lhs, const String& rhs) {
    // 处理其中一个字符串为空的情况
    if (lhs.length() == 0) {
        return rhs;
    }
    if (rhs.length() == 0) {
        return lhs;
    }

    // 计算拼接后的总长度:lhs长度 + rhs长度 + 1(空格) + 1(结束符)
    size_t totalLength = lhs.length() + rhs.length() + 2;
    char* newData = new char[totalLength];

    // 复制第一个字符串内容
    strcpy(newData, lhs.c_str());
    // 添加空格
    strcat(newData, " ");
    // 复制第二个字符串内容
    strcat(newData, rhs.c_str());

    // 创建并返回新的String对象
    String result(newData);
    delete[] newData; // 释放临时分配的内存
    return result;
}

3. 测试链式拼接功能

添加operator<<重载方便打印String对象,然后测试多字符串拼接:

// 重载输出运算符,方便打印String对象
std::ostream& operator<<(std::ostream& os, const String& str) {
    os << str.c_str();
    return os;
}

int main() {
    String s1("Hello");
    String s2("There");
    String s3("!");

    // 双字符串拼接
    String s4 = s1 + s2;
    std::cout << s4 << std::endl; // 输出:Hello There

    // 多字符串链式拼接
    String s5 = s1 + s2 + s3;
    std::cout << s5 << std::endl; // 输出:Hello There !

    return 0;
}

关键点说明

  • 非成员运算符重载:确保s1 + s2返回的临时String对象能继续和第三个字符串完成链式拼接。
  • 边界情况处理:当其中一个字符串为空时,直接返回另一个字符串,避免出现开头或结尾的多余空格。
  • 内存安全:所有动态分配的内存都做了正确释放,避免内存泄漏。

内容的提问来源于stack exchange,提问作者user26695080

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 23:03:25