c++ - 为什么这些字符串不会在 C++ 中连接?

标签 c++ string char string-concatenation

我有一个用 C++ 编写的两个测试程序的示例。第一个工作正常,第一个错误。请帮我解释一下这是怎么回事。

#include <iostream>
#include <string>
#include <stdint.h>
#include <stdlib.h>
#include <fstream>
using namespace std;

string randomStrGen(int length) {
static string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
string result;
result.resize(length);
for (int32_t i = 0; i < length; i++)
    result[i] = charset[rand() % charset.length()];
return result;
}

int main()
{
ofstream pConf;
pConf.open("test.txt");
pConf << "rpcuser=user\nrpcpassword=" 
     + randomStrGen(15)
     + "\nrpcport=14632"
     + "\nrpcallowip=127.0.0.1"
     + "\nport=14631"
     + "\ndaemon=1"
     + "\nserver=1"
     + "\naddnode=107.170.59.196";
pConf.close();
return 0;
}

它打开“test.txt”并写入数据,没问题。然而,这不会:

#include <iostream>
#include <string>
#include <stdint.h>
#include <stdlib.h>
#include <fstream>
using namespace std;

string randomStrGen(int length) {
static string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
string result;
result.resize(length);
for (int32_t i = 0; i < length; i++)
    result[i] = charset[rand() % charset.length()];
return result;
}

int main()
{
ofstream pConf;
pConf.open("test.txt");
pConf << "rpcuser=user\n"
     + "rpcpassword=" 
     + randomStrGen(15)
     + "\nrpcport=14632"
     + "\nrpcallowip=127.0.0.1"
     + "\nport=14631"
     + "\ndaemon=1"
     + "\nserver=1"
     + "\naddnode=107.170.59.196";
pConf.close();
return 0;
}

第二个程序的唯一区别是“rpcpassword”已移至下一行。

matthew@matthew-Satellite-P845:~/Desktop$ g++ test.cpp 
test.cpp: In function ‘int main()’:
test.cpp:23:6: error: invalid operands of types ‘const char [14]’ and ‘const char [13]’ to binary ‘operator+’ 
  + "rpcpassword="

最佳答案

C++ 中的字符串文字 ("foo") 不是 string 类型;它是 const char[x] 类型,其中 x 是字符串文字的长度加 1。并且字符数组不能与 + 连接。但是,字符数组可以字符串连接,结果是一个字符串,它可以进一步与字符数组连接。因此,"a"+ functionThatReturnsString() + "b" 有效,但 "a"+ "b" 无效。 (请记住,+ 是左结合的;它首先应用于最左边的两个操作数,然后应用于结果和第三个操作数,依此类推。)

关于c++ - 为什么这些字符串不会在 C++ 中连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28356983/

相关文章:

迷惑C开头

c++ - GCC 6.x 关于 lambda 可见性的警告

python - 如何将字符串列表更改为 float 列表

在 codeblock 中编译,但不在 hackerrank 中编译

c - 多次调用 char[] 立即返回函数 fprint

cygwin 终端中的 ruby​​ 读取字符

c++ - 静态链接具有较新平台 SDK 的库,可能吗?

c++ - boost ipc new 和 delete 运算符

c++ - 如果函数没有结束运行,请在 5 分钟内停止函数

c - C 中 char[] 和字符串的区别