【发布时间】:2015-02-06 01:10:45
【问题描述】:
我有一个我用 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="
【问题讨论】:
-
不同之处在于
std::string有operator+重载以与const char*连接。 -
Aasmund 的回答是正确的,但顺便说一下,相邻的字符串文字会在相当早的阶段被编译器连接起来(例如,“abc”“def”变成“abcdef”,即使它们位于不同的行中来源)。所以,如果你删除除
randomStrGen(15)之前和之后的所有'+',它不仅会正确编译,而且会使用更少的内存并运行得更快。 -
FWIW - 使用串联的示例 here...
标签: c++ string char string-concatenation