且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

嵌套类成员函数无法访问包含类的函数。为什么?

更新时间:2022-11-22 11:11:27

foo() A 的静态成员函数,并且您尝试在没有实例的情况下调用它。

嵌套类 B 是一个只有一些访问权限的独立类,并且没有关于 A 的现有实例的任何特殊知识。

foo() is a non-static member function of A and you are trying to call it without an instance.
The nested class B is a seperate class that only has some access privileges and doesn't have any special knowledge about existing instances of A.

如果 B 需要访问 A ,则必须提供引用:

If B needs access to an A you have to give it a reference to it, e.g.:

class A {
    class B {
        A& parent_;
    public:
        B(A& parent) : parent_(parent) {}
        void foobar() { parent_.foo(); }
    };
    B b_;
public:
    A() : b_(*this) {}
};