我需要在此類中實現這兩種方法。 Elem &運算符*()和Elem *運算符 - >()。唯一的問題是Iterator類是在Map類中定義的。 Elem在父類的專用部分中定義。問題在於我不允許修改該類的.h文件。從子類訪問私有結構
class Iterator{
public:
Iterator(){}
explicit Iterator(Elem *cur):_cur(cur) {}
Elem& operator*();
Elem* operator->();
// Iterator operator++(int);
bool operator==(Iterator it);
bool operator!=(Iterator it);
private:
Elem* _cur;
};
這是我嘗試實現的功能。然而,它不能正常工作,因爲它表示結構是私人的。
Map::Elem& Map::Iterator::operator*(Iterator it){
//do stuff
}
該類在另一個類中定義。哪個結構在private部分下定義。如果Elem結構是私有的,我不太確定我應該如何從Iterator類中返回Elem &或Elem *。然而我懷疑它與Elem * _cur有關;在Iterator類的私有函數中定義。
這是在Map類中定義的結構。如果這是有道理的..其私人...
private:
struct Elem {
KEY_TYPE key;
VALUE_TYPE data;
Elem *left;
Elem *right;
};
Elem *_root; // a dummy root sentinel
int _size;
如果我包括不起作用,這裏是完整的類定義。只是想包含上面的例子以包含更少的代碼。
#ifndef MAP_H
#define MAP_H
#include <iostream>
#include <string>
using namespace std;
typedef string KEY_TYPE;
typedef string VALUE_TYPE;
class Map{
struct Elem; //declaration of an interal structure needed below...
public:
//---Constructors and destructors---
Map(); // constructs empty Map
Map(const Map &rhs); // copy constructor
~Map(); // destructor
// assignment operator
Map& operator=(const Map &rhs);
// insert an element; return true if successful
bool insert(KEY_TYPE, VALUE_TYPE);
// remove an element; return true if successful
bool erase(KEY_TYPE);
// return size of the Map
int size() const;
// return an iterator pointing to the end if an element is not found,
// otherwise, return an iterator to the element
class Iterator;
Iterator find(KEY_TYPE) const;
// Iterators for accessing beginning and end of collection
Iterator begin() const;
Iterator end() const;
// overloaded subscript operator
VALUE_TYPE& operator[](KEY_TYPE);
// output the undering BST
ostream& dump(ostream& out) const;
// a simple Iterator, won't traverse the collection
class Iterator{
public:
Iterator(){}
explicit Iterator(Elem *cur):_cur(cur) {}
Elem& operator*();
Elem* operator->();
// Iterator operator++(int);
bool operator==(Iterator it);
bool operator!=(Iterator it);
private:
Elem* _cur;
};
private:
struct Elem {
KEY_TYPE key;
VALUE_TYPE data;
Elem *left;
Elem *right;
};
Elem *_root; // a dummy root sentinel
int _size;
// helper method for inserting record into tree.
bool insert(Elem *& root, const KEY_TYPE& key, const VALUE_TYPE& data);
// helper method for print tree
void printTree(ostream& out, int level, Elem *p) const;
// common code for deallocation
void destructCode(Elem *& p);
// common code for copy tree
void copyCode(Elem* &newRoot, Elem* origRoot);
};
ostream& operator<< (ostream&, const Map&);
#endif
任何幫助都會很棒。一直在谷歌上沒有這樣的運氣。
如果它應該可以被子類訪問,它將被標記爲'protected'。 – tadman
@tadman是否有辦法實現它目前的設置? –