#include <string>
#include <iostream>
int main()
{
std::string test("hello world ");
std::string label("label test");
test.append(&label[3]); //----- #1
std::cout << test << std::endl;
}
對於上面的代碼,我期望的是「hello world e」,但實際上它的輸出是「hello world el test」。它將位置3之後的所有字符附加到我的字符串test
。C++將一個字符從一個字符串追加到另一個字符串
在位置#1,如果我不把&跡象,會有編譯錯誤:
str_append.cpp:10:10: error: no matching member function for call to 'append'
test.append(label[3]);
~~~~~^~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:1516:19: note: candidate function not viable: no known conversion
from 'value_type' (aka 'char') to 'const value_type *' (aka 'const char *') for 1st argument; take the address of the argument with &
basic_string& append(const value_type* __s);
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:1513:19: note: candidate function not viable: no known conversion
from 'value_type' (aka 'char') to 'const std::__1::basic_string<char>' for 1st argument
basic_string& append(const basic_string& __str);
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:1525:9: note: candidate function template not viable: requires 2
arguments, but 1 was provided
append(_InputIterator __first, _InputIterator __last);
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:1532:9: note: candidate function template not viable: requires 2
arguments, but 1 was provided
append(_ForwardIterator __first, _ForwardIterator __last);
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:1515:19: note: candidate function not viable: requires 2
arguments, but 1 was provided
basic_string& append(const value_type* __s, size_type __n);
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:1517:19: note: candidate function not viable: requires 2
arguments, but 1 was provided
basic_string& append(size_type __n, value_type __c);
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:1514:19: note: candidate function not viable: requires at least 2
arguments, but 1 was provided
basic_string& append(const basic_string& __str, size_type __pos, size_type __n=npos);
^
1 error generated.
我能解決這個問題的唯一方法是將#1線更改爲:
test += label[3];
所以,我想知道這背後的邏輯是什麼? label[3]
不能返回單個字符嗎?爲什麼它失敗時,我只使用test.append(label[3]);
。爲什麼test += label[3];
成功?
在此先感謝。
又一個「我沒看過文檔」的問題。這個世界有什麼問題? * downvotes和哭泣* –