我有一個在C++中編寫的兩個測試程序的例子。第一個工作正常,第一個錯誤。請幫我解釋一下這裏發生了什麼。爲什麼這些字符串不會在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'已被移動到下一行。
[email protected]:~/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 *'連接。 – 2015-02-06 01:14:04
Aasmund的答案是正確的,但偶然相鄰的字符串文字會在編譯器的早期階段被串聯(例如,即使它們位於源中的不同行上,「abc」「def」也會變成「abcdef」)。因此,如果刪除'randomStrGen(15)'之前和之後的所有'+',它不僅能夠正確編譯,而且可以使用更少的內存並且運行得更快。 – 2015-02-06 01:21:05
FWIW - 使用連接的示例[here](http://ideone.com/MEoMgF)... – 2015-02-06 01:31:37