是不可能使用间接(取消引用)运算符取消引用存储在数组中的对象的指针,还是我做错了什么?为什么我不能使用间接运算符将指针取消引用一个数组元素的对象?
#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();
是这项工作? *(1).test() – cutzero
尝试:'(* v [1])。test()' - 你想要解引用的数组元素,而不是'test()'的返回值。 – Galik