我有一个用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="

最佳答案

"rpcuser=user\nrpcpassword=" + randomStrGen(15) + "\nrpcport=14632"个群组,例如("rpcuser=user\nrpcpassword=" + randomStrGen(15)) + "\nrpcport=14632"。在这里,+始终与类类型的参数一起使用,因此在重载解析后会得到std::string::operator+

"rpcuser=user\n" + "rpcpassword=" + randomStrGen(15)个群组,例如("rpcuser=user\n" + "rpcpassword=") + randomStrGen(15)。在这种情况下,第一个+用于两个非类类型,因此不会重载,并且语言不会为两个+值定义const char []。 (我来自旧C语言,所以我有点不只是将它们添加为char *并在运行时为您提供了不错的SIGSEGV。)

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

10-14 10:32