简体   繁体   English

C ++三元运算符字符串连接

[英]C++ ternary operator string concatenation

I have seen this question asked for other languages, but not C++. 我已经看到这个问题要求其他语言,但不是C ++。 Here's what I'm trying to do: 这是我正在尝试做的事情:

bool a = true;
string s;
s.append("a:" + (a? "true" : "false"));    
cout << s << endl;

I get a compiler error stating that I cannot add two pointers. 我收到一个编译器错误,指出我无法添加两个指针。 What gives? 是什么赋予了?

s.append(string("a:") + (a? "true" : "false"));

"true" , "false" , "a:" , "b:" and "c:" are pointers (raw char arrays, actually). "true""false""a:""b:""c:"是指针(实际上是原始字符数组)。 When you add them together with + (eg "a:" + "true" ) , then std::string is not involved, and it's only std::string which actually gives + the meaning of concatenation. 当你与一起添加它们+ (如"a:" + "true" ),那么std::string是不参与,这是唯一std::string这实际上赋予+拼接的意义。

Here's what I do in such situations: 这是我在这种情况下所做的事情:

s += "a:" + std::string(a ? "true" : "false");

Just noting this, but when C++14 comes around, this will become even easier. 只是注意到这一点,但是当C ++ 14出现时,这将变得更加容易。 Firstly, this can currently be written using operator+= instead of append : 首先,这可以使用operator+=而不是append来编写:

s += std::string("a:") + (a ? "true" : "false"); 

In C++14, there will be a standard operator""s , which means this is possible: 在C ++ 14中,将有一个标准的operator""s ,这意味着这是可能的:

s += "a:"s + (a ? "true" : "false"); 

However, the one that still makes the most sense to use in both cases, based on the shown code, is DigitalEye's answer , since it removes the need for a cast altogether. 然而,基于所显示的代码,在两种情况下仍然最有意义的是DigitalEye的答案 ,因为它完全不需要演员表。 I imagine your real code is different, though, which means this could soon be useful (or already, given a C++14 standard library implementation being in use). 我想你的真实代码是不同的,这意味着这很快就会有用(或者已经使用了C ++ 14标准库实现)。

Try 尝试

 bool a;

 string s;
 s.append(string("a:") + (a? "true" : "false"));

Because you try to concatenate two strings which are arrays of type char . 因为您尝试连接两个字符串,这些字符串是char类型的数组。 "a:" is of type const char[3] and you cannot concatenate such strings with + operator. "a:"const char[3]类型,你不能用+运算符连接这些字符串。 You have to use type string which has defined + operator which can be used to concatenate strings: 你必须使用定义了+运算符的类型string ,它可以用来连接字符串:

s.append(std::string("a:") + (a? "true" : "false"));

"a:" is char const[3] and (a? "true" : "false") is also char const[5] (for true) or char const[6] (for false), so you are applying + operator to two pointers. “a:”是char const [3]和(a?“true”:“false”)也是char const [5](对于true)或char const [6](对于false),所以你应用+运算符两个指针。

The code below will work, because you are calling the overloaded += of string class that takes char const* as parameter: 下面的代码将起作用,因为您正在调用带有char const *作为参数的重载的+ =字符串类:

s = "a:"
s +=  a ? "true": "false";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM