内部类访问外部类成员 [英] Inner Class access to Outer Class members
问题描述
我很困惑这个主题,基本上我有这个代码:
I'm very confused about this topic, basically I've this code:
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 。
This code give me a compiler error, so, I would to know if is possible to give the Inner Class the acces to the members of the Outer Class.
感谢。
推荐答案
嵌套类已经可以访问包含类的成员,假设它们有一个指针/引用要操作的包含类。您的迭代器将需要存储对外部类的引用,以便能够按照您的需要访问容器。
Nested classes already have access to the containing class's members, assuming they have a pointer/reference to the containing class upon which to operate. Your iterator will need to store a reference to the outer class in order to be able to access the container as you appear to want.
另请注意,受保护的数据通常是代码气味,通常应避免。如果适当,首选私人数据和受保护的接口。
Also note that protected data is usually a code smell and should typically be avoided. Prefer private data and a protected interface if appropriate.
编辑:除非这是严格地学习如何编写容器的练习,只需使用一个C ++标准容器作为向量
,它们已经很好地开发,调试和优化。
Unless this is strictly an exercise to learn how to program a container, just use one of the C++ standard containers such as vector
which are well developed, debugged, and optimized.
这篇关于内部类访问外部类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!