从指针访问[]运算符 [英] Accessing the [] operator from a pointer
问题描述
如果我定义了指向定义[]
运算符的对象的指针,是否有直接方法可以从指针访问该运算符?
If I define a pointer to an object that defines the []
operator, is there a direct way to access this operator from a pointer?
例如,在下面的代码中,我可以使用指针的->
运算符直接访问Vec
的成员函数(例如empty()
),但是如果要访问[]
运算符,我需要首先获取对该对象的引用,然后调用操作符.
For example, in the following code I can directly access Vec
's member functions (such as empty()
) by using the pointer's ->
operator, but if I want to access the []
operator I need to first get a reference to the object and then call the operator.
#include <vector>
int main(int argc, char *argv[])
{
std::vector<int> Vec(1,1);
std::vector<int>* VecPtr = &Vec;
if(!VecPtr->empty()) // this is fine
return (*VecPtr)[0]; // is there some sort of ->[] operator I could use?
return 0;
}
我很可能是错的,但是看起来执行(*VecPtr).empty()
的效率要比执行VecPtr->empty()
的效率低.这就是为什么我要寻找(*VecPtr)[]
的替代品.
I might very well be wrong, but it looks like doing (*VecPtr).empty()
is less efficient than doing VecPtr->empty()
. Which is why I was looking for an alternative to (*VecPtr)[]
.
推荐答案
您可以执行以下任一操作:
You could do any of the following:
#include <vector>
int main () {
std::vector<int> v(1,1);
std::vector<int>* p = &v;
p->operator[](0);
(*p)[0];
p[0][0];
}
顺便说一句,在std::vector
的特殊情况下,您可能还会选择:p->at(0)
,即使它的含义稍有不同.
By the way, in the particular case of std::vector
, you might also choose: p->at(0)
, even though it has a slightly different meaning.
这篇关于从指针访问[]运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!