内部类和对外部成员的访问 [英] Internal class and access to external members

查看:109
本文介绍了内部类和对外部成员的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直认为内部类可以访问其外部类中的所有数据,但具有代码:

I always thought that internal class has access to all data in its external class but having code:

template<class T>
class Vector
{
 template<class T>
 friend
std::ostream& operator<<(std::ostream& out, const Vector<T>& obj);
private:
 T** myData_;
 std::size_t myIndex_;
 std::size_t mySize_;
public: 
 Vector():myData_(nullptr),
  myIndex_(0),
  mySize_(0)
 { }
 Vector(const Vector<T>& pattern);
 void insert(const T&);
 Vector<T> makeUnion(const Vector<T>&)const;
 Vector<T> makeIntersection(const Vector<T>&)const;
 class Iterator : public std::iterator<std::bidirectional_iterator_tag,T>
 {
 private:
  T** itData_;
 public:
  Iterator()//<<<<<<<<<<<<<------------COMMENT
  { /*HERE I'M TRYING TO USE ANY MEMBER FROM Vector<T> AND I'M GETTING ERR SAYING:
   ILLEGAL CALL OF NON-STATIC MEMBER FUNCTION*/}

  Iterator(T** ty)
  { 
   itData_ = ty;
  }

  Iterator operator++()
  {
   return ++itData_;
  }

  T operator*()
  {
   return *itData_[0];
  }

  bool operator==(const Iterator& obj)
  {
   return *itData_ == *obj.itData_;
  }

  bool operator!=(const Iterator& obj)
  {
   return *itData_ != *obj.itData_;
  }

  bool operator<(const Iterator& obj)
  {
   return *itData_ < *obj.itData_;
  }
 };

 typedef Iterator iterator;

 iterator begin()const
 {
  assert(mySize_ > 0);
  return myData_;
 }

 iterator end()const
 {
  return myData_ + myIndex_;
 }
};

查看标记为COMMENT的行。

我可以在内部类中使用外部类的成员?

不要为命名而烦恼,它不是一个向量它是一个集合。

谢谢。

See line marked as COMMENT.
So can I or I can't use members from external class while in internal class?
Don't bother about naming, it's not a Vector it's a Set.
Thank you.

推荐答案

您需要将一个外部类的实例传递给内部类。换句话说,您的 Iterator 类必须具有对 Vector 方法的实例的引用(或指针)。最好的方法是让 Iterator 构造函数引用 Vector

You need to pass an instance of the external class to the internal class. In other words, your Iterator class must have a reference (or pointer) to an instance of Vector handy. The best way to do this is to have the Iterator constructor take a reference to a Vector.

Iterator(Vector& v) : vec_(v)
{
  vec_.do_something();
}

这篇关于内部类和对外部成员的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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