类的静态结构指针声明在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存储为结构对象而不是指向结构对象的指针会更容易,但很好奇这将如何工作。谢谢。

你不能把像Trie::EMPTY->ch = '.';Trie::EMPTY->ptrs = nullptr;这样的语句放在全局范围内,它们只能在函数、构造函数等内部执行。

尝试更多类似的东西:

/* 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;

现场演示

在命名空间(在任何函数外部(中,您只能放置声明。

像这样的陈述:

Trie::EMPTY->ch = '.';
Trie::EMPTY->ptrs = nullptr;

不允许放置在命名空间中,因为它们不是声明。

而且,这个声明:

Trie::EMPTY->ptrs = nullptr;

没有意义,因为对象ptrs不是指针,并且无法从nullptr初始化std::list

注意的是,代替C函数malloc(),你应该使用C++运算符new

这个定义:

TrieNode* Trie::EMPTY = (TrieNode*) malloc( sizeof(TrieNode) );

也是不正确的,因为您忘记指定限定符const

它应该像这样重写:

const TrieNode* Trie::EMPTY = new TrieNode { '.' };

这是一个演示程序

#include <iostream>
#include <list>
typedef struct tn {
char ch;
std::list<struct tn*> ptrs;
} TrieNode;
class Trie {
public:
static const TrieNode* EMPTY;
//... other member functions
};
// the definition below must be placed in a cpp module
// it presents here only for demonstration.
const TrieNode* Trie::EMPTY = new TrieNode { '.' };
int main() 
{
return 0;
}

在退出程序之前,您应该释放分配的内存。

您可以使用智能指针代替原始指针std::unique_ptr

最新更新