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.
Why does it need t开发者_开发百科o be dereferenced with parentheses?
Doesn't compile: *ItStr.c_str();
error C2039: 'c_str' : is not a member of 'std::vector<_Ty>::iterator'
Compiles/Works with parentheses around iterator: (*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())
.
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).
Because the .
operator has precedence over the *
operator. See this link
Without the brackets, *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:
- C++ Operator Precedence Table
Without the parentheses you are trying to dereference the entire statement ItStr.c_str()
.
With the parens around *ItStr
, you're dereferencing ItStr
and then taking the .c_str()
member of it. The arrow operator ->
can also be used in place of putting the parentheses around the dereferenced ItStr
.
As James et al have pointed out, it's an operator precedence issue.
精彩评论