Skip to content

Instantly share code, notes, and snippets.

@loosechainsaw
Created March 11, 2012 11:50
Show Gist options
  • Save loosechainsaw/2016165 to your computer and use it in GitHub Desktop.
Save loosechainsaw/2016165 to your computer and use it in GitHub Desktop.
Howto organise classes that have reference to each other
template<typename T>
class array{
public:
array(){
elements_ = new T[10];
size_ = 10;
}
array(int size){
elements_ = new T[size];
size_ = size;
}
~array(){
delete[] elements_;
}
array(const array& other){
this->size_ = other.size();
elements_ = new T[other.size()];
copy(other.elements_, &(other.elements_[other.size()]), elements_);
}
array& operator = (array const & other){
if(this == &other)
return *this;
T* elements = new T[other.size()];
delete[] elements_;
elements_ = elements;
copy(other.elements_, &(other.elements_[other.size()]), elements_);
return *this;
}
T& operator[](int index){
return elements_[index];
}
int size() const {
return size_;
}
private:
T* elements_;
int size_;
};
template<typename T>
class array_iterator{
public:
array_iterator(array<T>& source) : source_(source), index_(0){ }
array_iterator(array<T>& source, int index) : source_(source), index_(index){ }
array_iterator<T> begin() const{
return array_iterator<T>(source_, index_);
}
array_iterator<T> end() const{
return array_iterator<T>(source_, source_.size());
}
bool operator != (array_iterator<T> other){
return index_ != other.index_;
}
array_iterator<T>& operator++(){
index_++;
return *this;
}
T& operator*(){
return source_[index_];
}
private:
array<T>& source_;
int index_;
};
void custom_array_exp(bool run){
if(!run) return;
array<int> a(3);
for(int i = 0; i < a.size(); i++){
a[i] = (i + 1) * 3;
}
array_iterator<int> iterator(a);
for(array_iterator<int> i = iterator.begin(); i != iterator.end(); ++i){
cout << *i << endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment