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

14 c++ pointers operators operator-precedence dereference

是不是可以使用间接(取消引用)运算符取消引用指向存储在数组中的对象的指针,还是我做错了?

#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;
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

$ 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();
Run Code Online (Sandbox Code Playgroud)

son*_*yao 32

根据运算符优先级,operator.(成员访问运算符)具有比operator*(间接/解除引用运算符)更高的优先级,因此*(v[1]).test();等效于*((v[1]).test());,它是无效的.(你可以不叫test()v[1]这是A*通过opeartor.).

将其更改为

(*v[1]).test();
Run Code Online (Sandbox Code Playgroud)


Ser*_*gey 17

正确的方法是:

(*v[1]).test();
Run Code Online (Sandbox Code Playgroud)

在这里,您首先索引数组并获取指针(v[1]),然后取消引用指针(*v[1]),最后按对象值调用方法.

在您的示例中,您首先尝试test使用.on 来调用v[1],这是一个指针.只有在那之后你才解除引用方法的返回值,这也是无意义的test返回void.