嵌套类的类型不完整

Incomplete Type of Nested Class

本文关键字:类型 嵌套      更新时间:2023-10-16

我有一个以下形式的代码:

class Trie{
public:
    Trie( ) : root( new TrieNode( ) ){ };
    // Inserts a word into the trie.
    void insert( std::string word );
    // Returns if the word is in the trie.
    bool search( std::string word );
    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith( std::string prefix );
private:
    class TrieNode;
    std::unique_ptr<TrieNode> root;
};
class Trie::TrieNode{
public:
    TrieNode( ) : eow( false ){ };
    TrieNode* appendChar( char tar );
    void end( );
    bool isEnd( );
    TrieNode* getChar( char tar );
    int getInd( char tar );
private:
    std::array<std::unique_ptr<TrieNode>, 26> data;
    bool eow;                        // End of word
};

然而,在第三行,Trie(): root( new TrieNode() ),编译器继续抱怨TrieNode不完整。我该如何解决它?

谢谢!

TrieNode定义之后定义Trie的构造函数

class Trie::TrieNode{...}
// must be AFTTER the class Trie is fully defined
Trie::Trie( ) : root( new TrieNode( ) ){ };

否则Trie的构造函数需要TrieNode的完整定义,因为它需要构造一个新对象,因此您的错误。