Internal class and access to external members

微笑、不失礼 提交于 2020-01-04 09:22:11

问题


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_;
 }
};

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.


回答1:


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



回答2:


You cannot access fields or methods from the sourrounding class in C++!



来源:https://stackoverflow.com/questions/2659450/internal-class-and-access-to-external-members

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!