内部类访问外部类成员

时间:2011-04-20 14:47:26

标签: c++

我对这个话题非常困惑,基本上我有这段代码:

template <typename T>
class SListArray
{
public:
    class const_iterator
    {
    public:
        const_iterator(size_t i_currentNode = -1)
            :m_position(i_currentNode)
        {
        }

        T const& operator*() const
        {
            return m_data[m_position].element;
        }

        // ...

    protected:
        size_t m_position;
    };

    explicit SListArray();

    // ...

private:
    std::vector<Node<T>> m_data;

    // ...
};

这段代码给了我一个编译错误,所以,我想知道是否可以给Inner Class提供对外类成员的访问。

感谢。

5 个答案:

答案 0 :(得分:8)

嵌套类已经可以访问包含类的成员,假设它们具有指向操作的包含类的指针/引用。您的迭代器需要存储对外部类的引用,以便能够按照您的需要访问容器。

另请注意,受保护的数据通常是代码气味,通常应避免使用。如果合适,首选私有数据和受保护的接口。

编辑:除非这是一个学习如何编写容器的练习,否则只需使用一个C ++标准容器,例如vector,这些容器经过精心开发,调试和优化。

答案 1 :(得分:2)

是的,请使用朋友声明。

private:
  std::vector<Node<T> > m_data;
  friend class const_iterator;

更新:哦,您对m_data的访问权限是错误的。如果没有指向外部类实例的指针,内部类就无法访问外部类的成员。因此,您必须调整const_iterator类以存储指向外部类的指针/引用,并在operator*()中使用此指针/引用。

答案 2 :(得分:2)

正如Sjoerd已经回答的那样,您可以使用friend关键字授予访问权限。但是,如果您正在寻找Java风格的内部类,那么在C ++中就没有这样的东西。

答案 3 :(得分:0)

虽然让const_iterator成为SListArray的朋友可以解决您的问题,但我想知道您为什么不使用std::vector。为什么还有另一个新的通用类?

如果您正在寻找新名称,则可以typedef为:

typedef std::vector<Node<int>>                 NodeList;
typedef std::vector<Node<int>>::iterator       NodeIterator;
typedef std::vector<Node<int>>::const_iterator NodeConstIterator;

答案 4 :(得分:0)

传递参考:

class const_iterator {
public:
   const_iterator(ListArray<T> &arr) : arr(arr) { }
private:
   ListArray<T> &arr;
};

然后你也需要朋友的东西。