为什么我不能这样写代码:
int main()
{
std::map<std::string, int> m;
m.iterator it = m.find("five");
//~~~^~~~~
// nor like this:
m::iterator it = m.find("eight");
}
Run Code Online (Sandbox Code Playgroud)
你不能写m.iterator,因为iterator不是数据成员或成员函数,你不能operator.为它使用成员访问运算符(即)。(iterator是嵌套类型名称。)
你不能写m::iterator,因为m它不是类名或命名空间名称,你不能将它与范围运算符(即operator::)一起使用。
您可以使用auto(C++11 起) 来推导类型。
auto it = m.find("five"); // the type would be std::map<std::string, int>::iterator
Run Code Online (Sandbox Code Playgroud)
或通过decltype(C++11 起)获取类型。
decltype(m.begin()) it = m.find("five"); // the type would be std::map<std::string, int>::iterator
decltype(m)::iterator it = m.find("five"); // same as above
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
68 次 |
| 最近记录: |