首页 > 解决方案 > C++中类的静态结构指针声明

问题描述

给定以下代码段:

   /* trie.h file */

using namespace std;
#include <list>

typedef struct tn {
         char ch;
         list<struct tn*> ptrs;
} TrieNode;

class Trie {
public:
        static const TrieNode* EMPTY;
        //... other member functions
};

/* trie.cpp file */

#include "trie.h"

// declare, define static variables of the Trie class
TrieNode* Trie::EMPTY = (TrieNode*) malloc( sizeof(TrieNode) ); // <-- seems to work fine

// the statements below seem to yield errors
Trie::EMPTY->ch = '.';
Trie::EMPTY->ptrs = nullptr;

如果我尝试实例化静态常量变量的结构成员变量,则会收到错误消息:“此声明没有存储类型或类型说明符” EMPTY。我知道存储EMPTY为结构对象而不是指向结构对象的指针会更容易,但很好奇这将如何工作。谢谢。

标签: c++pointersstatic

解决方案


You can't put statements like Trie::EMPTY->ch = '.'; and Trie::EMPTY->ptrs = nullptr; in global scope, they can only be executed inside of functions, constructors, etc.

Try something more like this instead:

/* trie.h file */

#include <list>

struct TrieNode {
    char ch;
    std::list<TrieNode*> ptrs;
};

class Trie {
public:
    static const TrieNode* EMPTY;
    //... other member functions
};
/* trie.cpp file */

#include "trie.h"

// declare, define static variables of the Trie class
static const TrieNode emptyNode{'.'};
const TrieNode* Trie::EMPTY = &emptyNode;

Live Demo


推荐阅读