Why can't I dereference a pointer to an object that's an array-element using the indirection operator?

百般思念 提交于 2021-02-16 09:48:53

问题


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;
}

Here is the error I get:

$ 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:


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..)

Change it to

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



回答2:


The proper way is this:

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

Here you first index the array and get the pointer (v[1]), then you dereference the pointer (*v[1]) and finally call the method by object value.

In your example you first tried to call test using . on v[1], which is a pointer. And only after that you dereferenced the method's return value, which is also nonsense as test returns void.



来源:https://stackoverflow.com/questions/39030947/why-cant-i-dereference-a-pointer-to-an-object-thats-an-array-element-using-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!