我正在研究一个看起来像这样的容器类:

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

有帮助吗?

解决方案

向前宣布一个在另一个之前。您可以在另一个类的声明中使用对前向声明的类的引用,因此这应该有效:

class hexFile; // forward

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

class hexFile {
   ...
};

其他提示

使用转发参考

启动 .h 文件
class hexFile;

然后按照类hexIterator 的完整定义(因为它只需要指针 hexFile )进行编译,然后完整 class hexFile 的定义(现在编译得很好,因为那时编译器知道 hexIterator 的所有内容。)

.cpp 文件中,由于您包含 .h ,当然所有内容都是已知的,您可以按照任何顺序实现这些方法。

我建议将定义与类的声明分开。在头文件中,forward声明hexFile类,然后在头文件中完全声明它们。然后,您可以在关联的源文件中更详细地定义各个类。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top