我正在研究一些 C 特性,嘗試進行一些實驗。但是,我卡在編譯錯誤的地方:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "some string";
auto &c = str.begin(); // compile error
*c = toupper(*c);
cout << *c << ", str: " << str << endl;
}
我不知道為什么它不被接受。我的想法是c具有型別char *(指向 a 的指標char),所以這就是我如上所述撰寫的原因。但是為什么編譯失敗呢?
錯誤 C2440 無法將 'std::_String_iteratorstd::_String_val<std::_Simple_types<_Elem>>' 轉換為 'std::_String_iterator<std::_String_val<std::_Simple_types<_Elem
PS:我首先嘗試的另一種方法是可以的。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "some string";
auto &c = *str.begin(); // success
c = toupper(c);
cout << c << ", str: " << str << endl;
}
uj5u.com熱心網友回復:
begin()按值回傳迭代器,而不是參考。不允許形成非const左值參考。
這樣做const會延長回傳的迭代器的壽命,然后程式將編譯:
const auto &c = str.begin();
另一方面,迭代器被認為復制起來很便宜,并且來自連續容器的迭代器通常被實作為純指標。慣用的方法是:
auto c = str.begin();
在您的第二個示例中,形成對第一個元素的參考的慣用方法是:
auto& c = str.front();
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/485500.html
標籤:c 11
上一篇:decltype()的回傳型別
下一篇:具有已實作函式的結構向量中的錯誤
