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

C++中如何重载operator+实现向vector首尾添加元素

解决自定义String类的operator+重载问题

核心问题分析

你的代码存在三个关键问题:

  1. 成员函数形式的operator+只能处理左操作数为String对象的场景(如P + 'e'),无法处理'e' + P这种左操作数是char的情况——因为成员函数的左操作数固定为类实例,必须用全局非成员函数重载才能支持这种反向操作。
  2. 现有operator+直接修改原对象并返回vector,违背了+运算符的常规语义:+应该生成新对象,原对象保持不变。
  3. 移动构造函数实现错误:vector是对象而非指针,不能赋值为nullptr,且未正确使用移动语义转移资源。

修正后的完整代码

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

template <class T>
class String
{
public:
    vector<T> ptr_string;

    // 默认构造函数:空字符串
    String() = default;

    // 拷贝构造函数
    String(const String& other)
    {
        ptr_string.reserve(other.getLength());
        copy(other.ptr_string.begin(), other.ptr_string.end(), back_inserter(ptr_string));
    }

    // 重复n次字符的构造函数
    String(T symbol, int n)
    {
        ptr_string.resize(n, symbol);
    }

    // 移动构造函数:正确使用移动语义
    String(String&& a) noexcept
        : ptr_string(move(a.ptr_string))
    {}

    // 获取字符串长度
    int getLength() const
    {
        return ptr_string.size();
    }

    // 打印字符串
    void printString() const
    {
        for (const auto& c : ptr_string)
        {
            cout << c;
        }
        cout << endl;
    }

    // 成员函数:String + char,在末尾添加字符,返回新String
    String operator+(T c) const
    {
        String result(*this);
        result.ptr_string.push_back(c);
        return result;
    }

    // 成员函数:String + String,拼接两个字符串,返回新String
    String operator+(const String& other) const
    {
        String result(*this);
        result.ptr_string.insert(result.ptr_string.end(), other.ptr_string.begin(), other.ptr_string.end());
        return result;
    }
};

// 全局非成员函数:char + String,在开头添加字符,返回新String
template <class T>
String<T> operator+(T c, const String<T>& str)
{
    String<T> result;
    result.ptr_string.push_back(c);
    result.ptr_string.insert(result.ptr_string.end(), str.ptr_string.begin(), str.ptr_string.end());
    return result;
}

int main()
{
    String<char> P = String<char>('P', 10);

    // 测试末尾添加字符,原P保持不变
    String<char> P_with_e = P + 'e';
    P_with_e.printString(); // 输出:PPPPPPPPPPe

    // 测试开头添加字符,原P保持不变
    String<char> e_with_P = 'e' + P;
    e_with_P.printString(); // 输出:ePPPPPPPPPP

    // 原对象未被修改
    P.printString(); // 输出:PPPPPPPPPP
}

关键修正说明

  1. 全局operator+重载:针对char + String的场景,通过全局函数实现——先创建空String,添加目标字符后,再插入原String的所有元素,最终返回新对象。
  2. 运算符语义修正:所有operator+都返回新的String实例,不修改原对象,完全符合C++中+运算符的设计习惯。
  3. 移动构造函数修复:使用std::move转移原对象的vector资源,避免不必要的拷贝,同时移除错误的nullptr赋值操作。
  4. 构造函数优化:用resize简化重复字符构造逻辑,用copy算法优化拷贝构造过程,提升代码简洁性和效率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 23:15:48