2009-06-18 42 views
1

我工作的一個容器類,它看起來是這樣的:C++集裝箱/迭代器依賴性問題

class hexFile { 
public: 
    HANDLE theFile; 
    unsigned __int64 fileLength; 
    hexFile(const std::wstring& fileName) 
    { 
     theFile = CreateFile(fileName.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL); 
     if (theFile == INVALID_HANDLE_VALUE); 
     { 
      throw std::runtime_error(eAsciiMsg("Could not open file!")); 
     } 
     BY_HANDLE_FILE_INFORMATION sizeFinder; 
     GetFileInformationByHandle(theFile, &sizeFinder); 
     fileLength = sizeFinder.nFileSizeHigh; 
     fileLength <<= 32; 
     fileLength += sizeFinder.nFileSizeLow; 
    }; 
    ~hexFile() 
    { 
     CloseHandle(theFile); 
    }; 
    hexIterator begin() 
    { 
     hexIterator theIterator(this, true); 
     return theIterator; 
    }; 
    hexIterator end() 
    { 
     hexIterator theIterator(this, false); 
     return theIterator; 
    }; 
}; 

而一個迭代器類來匹配,看起來像這樣:

class hexIterator : public std::iterator<std::bidirectional_iterator_tag, wchar_t> 
{ 
    hexFile *parent; 
public: 
    bool highCharacter; 
    __int64 filePosition; 
    hexIterator(hexFile* file, bool begin); 
    hexIterator(const hexIterator& toCopy); 
    ~hexIterator(); 
    hexIterator& operator++() 
    { 
     return ++this; 
    } 
    hexIterator& operator++(hexIterator& toPlus); 
    hexIterator& operator--() 
    { 
     return --this; 
    } 
    hexIterator& operator--(hexIterator& toMinus); 
    hexIterator& operator=(const hexIterator& toCopy); 
    bool operator==(const hexIterator& toCompare) const; 
    bool operator!=(const hexIterator& toCompare) const; 
    wchar_t& operator*(); 
    wchar_t* operator->(); 
}; 

我的問題是......兩個班都需要以另一個來實施。例如,我不確定如何引用迭代器中的容器,因爲在定義迭代器時,容器尚未定義。

如何做到這一點?

Billy3

回答

5

向前聲明一個在另一個之前。你可以在另一個類的聲明中使用引用向前聲明的類,所以這應該工作:

class hexFile; 

然後用完整的定義如下:

class hexFile; // forward 

class hexIterator : ,,, { 
    ... 
}; 

class hexFile { 
    ... 
}; 
+0

Upvoted for a correct answer,checkmarked for the最快的一個;) – 2009-06-18 21:35:34

3

以正參考啓動.h文件(因爲它只需要指針hexFile),那麼完全確定class hexFile(現在編譯就好了,因爲編譯器知道關於hexIterator的所有內容)。

.cpp文件中,由於您包含.h當然,所有內容都是已知的,您可以按照您希望的任何順序執行這些方法。

2

我會建議從類的聲明中分離出定義。在頭文件中,forward聲明hexFile類,然後在頭文件中完全聲明它們。然後,您可以在關聯的源文件中更詳細地定義各個類。