简体   繁体   English

为什么解引用字符串向量迭代器需要括号?

[英]Why does dereferencing a string vector iterator need parentheses?

vector<string> MyStrings;
vector<string>::iterator ItStr;

I'm using c_str() to return the pointer to the string.我正在使用c_str()来返回指向字符串的指针。

Why does it need to be dereferenced with parentheses?为什么需要用括号取消引用?

Doesn't compile: *ItStr.c_str();不编译: *ItStr.c_str();

error C2039: 'c_str': is not a member of 'std::vector<_Ty>::iterator'错误 C2039:“c_str”:不是“std::vector<_Ty>::iterator”的成员

Compiles/Works with parentheses around iterator: (*ItStr).c_str();编译/使用迭代器周围的括号: (*ItStr).c_str();

If you could point me (no pun intended) in the right direction I would appreciate it.Thanks!如果您能指出我(没有双关语)正确的方向,我将不胜感激。谢谢!

. has higher precedence than the unary * .比一元*具有更高的优先级。

*ItStr.c_str() is as if you had said *(ItStr.c_str()) . *ItStr.c_str()就像你说过*(ItStr.c_str())

You can, of course, just use ItStr->c_str() , since (*x).y is equivalent to x->y (at least for pointers and iterators; you can, of course, overload the operators for your own types such that they are not consistent, but you'd be crazy to do so).当然,您可以只使用ItStr->c_str() ,因为(*x).y等效于x->y (至少对于指针和迭代器而言;当然,您可以为自己的类型重载运算符这样它们就不一致了,但是这样做会很疯狂)。

Because the .因为. operator has precedence over the * operator.运算符优先于*运算符。 See this link看到这个链接

Without the brackets, *ItStr.c_str();没有括号, *ItStr.c_str(); is interpreted as:被解释为:

*(ItStr.c_str());

which obviously is wrong, and which you perhaps didn't intend.这显然是错误的,而且您可能并不打算这样做。 Its interpreted that way, because .它是这样解释的,因为. operator has higher precedence than * operator.运算符的优先级高于*运算符。 To avoid that you need to use brackets here:为避免这种情况,您需要在此处使用括号:

(*ItStr).c_str();

So that it can be interpreted correctly - the way you intend it to be interpreted.以便它可以被正确解释 - 您打算解释它的方式。

Have a look at:看一下:

Without the parentheses you are trying to dereference the entire statement ItStr.c_str() .如果没有括号,您将尝试取消引用整个语句ItStr.c_str()

With the parens around *ItStr , you're dereferencing ItStr and then taking the .c_str() member of it.使用*ItStr周围的括号,您将取消引用ItStr ,然后获取它的.c_str()成员。 The arrow operator -> can also be used in place of putting the parentheses around the dereferenced ItStr .箭头运算符->也可以用来代替在取消引用的ItStr周围放置括号。

As James et al have pointed out, it's an operator precedence issue.正如 James 等人所指出的,这是一个运算符优先级问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM