[英]Why is it that, when I dereference an array pointer, the resulting value is a pointer to the first element of the array, not the entire array object?
[英]Why can't I dereference a pointer to an object that's an array-element using the indirection operator?
是不是可以使用间接(取消引用)运算符取消引用指向存储在数组中的对象的指针,还是我做错了?
#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();
根据运营商Precedence , operator.
(成员访问运算符)的优先级高于operator*
(间接/解除引用运算符),所以*(v[1]).test();
相当于*((v[1]).test());
,这是无效的。 (你不能在v[1]
上调用test()
,这是通过opeartor.
A*
。)
将其更改为
(*v[1]).test();
正确的方法是:
(*v[1]).test();
在这里,您首先索引数组并获取指针( v[1]
),然后取消引用指针( *v[1]
),最后按对象值调用方法。
在您的示例中,您首先尝试使用调用test
.
在v[1]
,这是一个指针。 只有在那之后你才取消引用方法的返回值,这也是无意义的,因为test
返回void。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.