为什么我不能使用间接运算符取消对一个对象的指针,该对象是一个数组元素? [英] Why can't I dereference a pointer to an object that's an array-element using the indirection operator?

查看:66
本文介绍了为什么我不能使用间接运算符取消对一个对象的指针,该对象是一个数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否不可能使用indirection(dereference)运算符取消对存储在数组中的对象的指针的引用,或者我做错了什么?

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

这是我得到的错误:

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

推荐答案

根据运算符优先级 operator.(成员访问运算符)的优先级高于 operator * (间接/取消引用运算符),因此 *(v [1]).test(); 等效于 *((v [1]).test()); ,这是无效的.(您不能通过 opeartor在 v [1] 上的 A * 上调用 test()..)

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

将其更改为

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

这篇关于为什么我不能使用间接运算符取消对一个对象的指针,该对象是一个数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆