为什么我不能使用间接运算符取消引用指向作为数组元素的对象的指针?

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();

正确的方法是这样的:

(*v[1]).test();

这里首先索引数组并获取指针(v[1]),然后解引用指针(*v[1]),最后通过对象值调用方法。

在您的示例中,您首先尝试使用 v[1] 上的 . 调用 test,这是一个指针。只有在那之后你才取消引用方法的 return 值,这也是无稽之谈,因为 test returns void.

根据 Operator Precedenceoperator.(成员访问运算符)的优先级高于 operator*(indirection/dereference 运算符),因此 *(v[1]).test(); 是等价的到 *((v[1]).test());,这是无效的。 (您不能通过 opeartor.v[1] 上调用 test(),即 A*。)

改为

(*v[1]).test();