嵌套类成员函数无法访问包含类的函数。为什么? [英] Nested Class member function can't access function of enclosing class. Why?

查看:295
本文介绍了嵌套类成员函数无法访问包含类的函数。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅下面的示例代码:

Please see the example code below:

class A
{
private:
    class B
    {
    public:
        foobar();
    };
public:
    foo();
    bar();
};

B实现:

A::foo()
{
    //do something
}

A::bar()
{
    //some code
    foo();
    //more code
}

A::B::foobar()
{
    //some code
    foo(); //<<compiler doesn't like this
}

调用foobar()方法中的foo()。以前,我有foo()作为A类的私有成员函数,但改为公共假设B的函数不能看到它。当然,它没有帮助。我试图重用A的方法提供的功能。为什么编译器不允许这个函数调用?正如我看到的,它们是同一封闭类(A)的一部分。我认为用于在C ++标准中封装类的嵌套类meebers的辅助功能问题已解决。

The compiler flags the call to foo() within the method foobar(). Earlier, I had foo() as private member function of class A but changed to public assuming that B's function can't see it. Of course, it didn't help. I am trying to re-use the functionality provided by A's method. Why doesn't the compiler allow this function call? As I see it, they are part of same enclosing class (A). I thought the accessibility issue for nested class meebers for enclosing class in C++ standards was resolved.

如何在不重写相同方法的情况下实现我想要做的事情(foo())for B,保持B嵌套在A?

How can I achieve what I am trying to do without re-writing the same method (foo()) for B, which keeping B nested within A?

我使用VC ++编译器ver-9(Visual Studio 2008)。感谢您的帮助。

I am using VC++ compiler ver-9 (Visual Studio 2008). Thank you for your help.

推荐答案

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

这篇关于嵌套类成员函数无法访问包含类的函数。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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