Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 是否可能使操作员过载+;用字符串?_C++_String_C++11_Concatenation - Fatal编程技术网

C++ 是否可能使操作员过载+;用字符串?

C++ 是否可能使操作员过载+;用字符串?,c++,string,c++11,concatenation,C++,String,C++11,Concatenation,我想简化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

我想简化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;
}
这个方法不起作用,我得到一个编译器错误

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

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


从C++11开始,就有文字运算符可用。他们使写作成为可能

"count "_s
而不是

std::string("count ")
此类运算符的定义如下(以下文字运算符的名称为
\u s
;对于自定义文字运算符重载,它们必须以下划线开头):

然后,你的表情变成

"count "_s + 6
在C++14中,这样的运算符是,并且命名更方便
s
(标准可能会使用运算符名称,但不带前导下划线),因此

"count "s + 6

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

您可以通过使用用户定义的文本动态构造字符串,从而使事情变得更容易接受:

"count"s + 3.1415;

注意到这是一个C++ 14的特性,C++编译器可能支持或不支持它。

询问C++,为什么要为不同的语言添加标签?(反问,不要)是的,我使用C++,但是我相信C中也有重载操作符,但不确定。很抱歉,如果你不知道,你显然不知道C。所以请遵守规则,不要为你不知道的语言添加标签。(注意,第一句话暗示C不允许用户重载运算符)感谢您提供的信息,我将记住它
“s
是C++14的一个特性。这被标记为C++11。
“s
是C++14的一项功能。这被标记为C++11。我清楚地提到它是C++14。它不会使答案无效;这是一个原始海报可能根本不知道的选项。
"count "s + 6
"count"s + 3.1415;