为什么我不能使用间接运算符取消引用指向作为数组元素的对象的指针? [英] Why can't I dereference a pointer to an object that's an array-element using the indirection operator?
问题描述
是否无法使用间接(取消引用)运算符取消引用指向存储在数组中的对象的指针,或者我做错了什么?
Is it not possible to dereference a pointer to an object that's stored in an array using the indirection(dereference) operator or am I doing something wrong?
#include <iostream>
class A {
public:
virtual void test() {
std::cout << "A\n";
}
};
class B : public A {
public:
void test() {
std::cout << "B\n";
}
};
int main() {
A* v[2];
v[0] = new A();
v[1] = new B();
v[0]->test();
*(v[1]).test(); // Error! If the arrow operator is used instead
// though, the code compiles without a problem.
return 0;
}
这是我得到的错误:
$ g++ -std=c++11 test.cpp && ./a.out
test.cpp: In function ‘int main()’:
test.cpp:26:13: error: request for member ‘test’ in ‘v[1]’, which is of
pointer type ‘A*’ (maybe you meant to use ‘->’ ?)
*(v[1]).test();
推荐答案
根据 OperatorPrecedence, operator.
(member access operator) 比 operator*
(indirection/dereference operator) 有更高的优先级,所以 *(v[1]).test();
等价于 *((v[1]).test());
,这是无效的.(您不能通过 opeartor.
在 v[1]
上调用 test()
,也就是 A*
.)
According to the Operator Precedence, operator.
(member access operator) has higher precedence than operator*
(indirection/dereference operator) , so *(v[1]).test();
is equivalent to *((v[1]).test());
, which is not valid. (You can't call test()
on v[1]
which is A*
via opeartor.
.)
改成
(*v[1]).test();
这篇关于为什么我不能使用间接运算符取消引用指向作为数组元素的对象的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!