c++ - 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
为结构对象而不是指向结构对象的指针会更容易,但很好奇这将如何工作。谢谢。
解决方案
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;
推荐阅读
- angularjs - 角度代码未执行
- android - Cognito "redirect URL" using Android SDK
- docx - Pandoc Word to Dokuwiki heading conversion
- c# - How to unit test a vsix project?
- excel - Excel 2013:行索引数组的多个搜索条件
- javascript - Cookie expiration date equals -1
- php - 条带将元数据传递给客户条带时出现无效哈希错误
- linux - 无法在 Shell 脚本中保存进程的进程 ID
- angular - Angular 6 库
- ios - iOS: Error Domain=NSCocoaErrorDomain Code=132001 '-save: on the context aborted' 在后台使用更新数据库核心数据/推送通知