为什么这个语法无效?矢量指针->[0]
在C++
中,为什么vector
中的以下元素访问无效?
void foo(std::vector<int>* vecPtr) {
int n = vecPtr->size(); // ok
int a = vecPtr->[0]; // invalid
}
相反,我们必须编写
(*vecPtr)[0] = 1;
我认为更麻烦的操作,operator[] 调用应该具有与方法调用相同的语法,而且我讨厌额外的星号和括号。 (我知道 C++ 有很多更严重的问题,但是每次我必须键入它时,这个问题都会让我烦恼......)
In C++
, why is the following element access in a vector
invalid?
void foo(std::vector<int>* vecPtr) {
int n = vecPtr->size(); // ok
int a = vecPtr->[0]; // invalid
}
Instead, we have to write the more cumbersome
(*vecPtr)[0] = 1;
I think, the operator[]
call should just have the same syntax like a method call, and I hate the extra star and parentheses. (I know C++ has a lot more serious issues, but this one annoys me every time when I have to type it ...)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为该语言期望成员出现在
->
之后。语言就是这样构成的。如果您愿意,可以使用函数调用语法如果您必须按顺序执行此操作很多,使用
[0]
而不是括号可以大大提高可读性否则,对于一个级别,我发现
(*vecPtr)[0]
对我来说完全可读。It's because the language expects a member to appear after
->
. That's how the language is made up. You can use the function call syntax, if you likeIf you have to do this a lot in sequence, using
[0]
instead of the parentheses can improve readability greatlyOtherwise, for one level, i find
(*vecPtr)[0]
is perfectly readable to me.除了 litb 的好答案 我应该说
中有一个函数
类,允许您按如下方式使用它:at
>vector此成员函数和成员运算符函数
operator[]
之间的区别在于vector::at
发出信号如果请求的位置超出范围,则抛出out_of_range
异常。In addition to litb's nice answer I should say that there is a function
at
invector
class that allows you to use it as follows:The difference between this member function and member operator function
operator[]
is thatvector::at
signals if the requested position is out of range by throwing anout_of_range
exception.您似乎已经知道这应该是无效语法,那么问题是什么?唯一的书面答案是“因为这就是语言的书写方式”。
从语义上讲,这是因为 [] 运算符本质上是在说“计算所提供地址的偏移量”;它不是一个方法,而是一个运算符。您给出的语法感觉并没有什么意义。
另外,因为您描述的语法看起来很糟糕,因为您只是指向一个裸运算符而不是预期的成员。
如果您想更直接地了解间接(符号崩溃),请考虑使用引用。
You seem to know already that that is supposed to be invalid syntax, so what's the question? The only answer as written is "because that's the way the language is written".
Semantically, it's because that [] operator is essentially saying "compute offset from the supplied address"; it's not a method, it's an operator. The syntax you give just doesn't really feel like it makes sense.
Also, because the syntax you describe looks terrible, as you're just pointing at a bare operator instead of the expected member.
Consider using references if you want to be more direct about your indirection (symbol crash).