【问题标题】:Is it possible to overload the operator + with char strings?是否可以用 char 字符串重载运算符 + ?
【发布时间】:2016-03-02 16:06:21
【问题描述】:

我想像在java中一样简化字符串的使用。

所以我可以写"count "+6; 并得到一个字符串“count 6” 使用 std::string 可以连接两个字符串或 std::string 与 char 字符串。

我写了两个函数

template<typename T>
inline static std::string operator+(const std::string str, const T gen){
    return str + std::to_string(gen);
}

template<typename T>
inline static std::string operator+(const T gen, const std::string str){
    return std::to_string(gen) + str;
}

将 std::string 与数字连接,但不能写像 "count "+6; 这样的东西,因为 "count " 是 const char[] 而不是 std::string。

它适用于 std::string("count")+" is "+6+" and it works also with double "+1.234; ,但那不是很漂亮 =)

是否有可能在不从 std::string("") 开始的情况下做同样的事情

template<typename T>
inline static std::string operator+(const char* str, const T gen){
    return str + std::to_string(gen);
} 

这个方法不起作用,我得到一个编译器错误

error: invalid operands of types 'const char*' and 'const char [1]' to binary 'operator+'

【问题讨论】:

  • 问C++,你为什么要为不同的语言添加标签? (反问,只是不要
  • 是的,我正在使用 c++,但我相信在 c 中也可以使用重载运算符,但不确定。对不起,如果没有
  • 好吧,你显然不知道 C。所以只要遵守规则,不要为你不知道的语言添加标签。 (注意第一句暗示 C 不允许用户重载操作符)
  • 谢谢你的信息,我会记住的

标签: c++ string c++11 concatenation


【解决方案1】:

没有。您不能为内置类型重载运算符only;操作中涉及的两种类型之一必须是类类型或枚举。

您可以通过使用用户定义的文字即时构造字符串来让事情变得更可口:

"count"s + 3.1415;

请注意,这是一个 C++14 功能,您的编译器可能支持也可能不支持。

【讨论】:

  • 我明确提到它是 C++14。它不会使答案无效;这是原始发布者可能根本不知道的选项。
【解决方案2】:

重载运算符时,至少有一个操作数必须是用户类型(而std 库中的类型被视为用户类型)。换句话说:不是operator+ 的两个操作数都可以是内置类型。


自 C++11 起,有可用的文字运算符。它们使写作成为可能

"count "_s

而不是

std::string("count ")

这样的运算符是这样定义的(以下文字运算符的名称是_s;它们必须以下划线开头,以便自定义文字运算符重载):

std::string operator ""_s(const char *str, std::size_t len) {
    return std::string(str, len);
}

那么,你的表情就变成了

"count "_s + 6

在C++14中,这样的操作符是already available,更方便命名为s(标准可能使用不带下划线前导的操作符名称),所以变成了

"count "s + 6

【讨论】:

    猜你喜欢
    • 2017-05-06
    • 2017-02-05
    • 1970-01-01
    • 2015-01-01
    • 2012-09-04
    • 2010-10-20
    • 2010-10-21
    • 1970-01-01
    • 2023-04-05
    相关资源
    最近更新 更多