通过多个指针调用成员函数

时间:2017-01-01 03:15:10

标签: c++

我有一个类(C),其成员类(B)跟踪第三类(A)。通过C和B调用A的公共成员函数的正确语法是什么?或者我搞砸了指针?

#include <iostream>

class A
{
    public:
        void Hello() const {std::cout<<"World."<<std::endl;};
};

class B
{
    const A* aa;                    // Pointer can change, data cannot.

    public:
        const A* *const aaa;        // Pointer and pointed value are const.

        B() : aaa{&aa} {};
        void SetPointerToA(const A& aRef) {aa = &aRef;};
};

class C
{
    B b;

    public:
       B* bb;                       // Provide access to public members of B.

       C() : bb{&b} {};
};

int main()
{
    A aTop;
    C c;

    c.bb->SetPointerToA(aTop);      // Tell c.b to modify itself. No problems here.

    c.bb->aaa->Hello();             // <==== Does not compile.

    return 0;
}

gcc 5.2.0抱怨调用Hello():

error: request for member 'A:: Hello' in '*(const A**)c.C::bb->B::aaa',
which is of pointer type 'const A*' (maybe you meant to use '->' ?)

1 个答案:

答案 0 :(得分:3)

如果你密切注意,你会发现aaa是一个双指针。因此,它应该是:

(*c.bb->aaa)->Hello();

话虽如此:这些课看起来非常脆弱。他们don't comply with the Rule Of Three,因此,事情会在每一个可能的机会中破裂......