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

Mat*_*ell 0 c++ string string-concatenation char

我有一个用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;
}
Run Code Online (Sandbox Code Playgroud)

它打开'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;
}
Run Code Online (Sandbox Code Playgroud)

第二个程序的唯一区别是'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="
Run Code Online (Sandbox Code Playgroud)

Aas*_*set 5

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

  • OP应该只删除`+`,因为两个连续的字符串文字会自动连接. (3认同)