类的静态结构指针声明在C++
Class's static struct pointer declaration in 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
。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 未在作用域中声明unordered_map
- C++避免重复声明的语法是什么
- 如何确保C++函数在定义之前声明(如override关键字)
- 错误:未在此范围内声明'reverse'
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 为什么在定义函数之前先声明它
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- #ifdef和未声明的标识符
- 没有显式声明的int[]中的foreach
- 在基于范围的for循环中使用结构化绑定声明
- 在将变量声明为引用时,堆在释放后使用
- C++:无法访问声明的受保护成员
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- 在函数内部的声明中初始化数组,并在外部使用它
- Visual Studio中的函数声明和函数定义问题
- c++类声明时,相同的例程,不同的成员变量类型
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别