我想用 C++ 创建八叉树数据结构。我有一个头文件,看起来像这样:
class Octree
{
public:
typedef struct node
{
int value;
node *child[8];
}node;
Octree();
~Octree();
int convert(int sorszam);
void clear(struct node*);
node* search(int dec,int oct);
};
我想在 .cpp 文件中编写搜索功能,但我总是收到一条错误消息。这是 .cpp 代码:
node* Octree::search(int dec, int oct) {
//doing something here
return nullptr;
}
错误信息是:
declaration is incompatible with "Octree::node *Octree::search(int dec, int oct)" (declared at line 19 of "c:\Users\xxx\Documents\Visual Studio 2015\Projects\xxx\xxx\Octree.h")
我不知道发生了什么,因为这两个函数的类型是一样的。我做错了什么?
最佳答案
节点的 typedef
作用域为类。当你使用
node* Octree::search(int dec, int oct)
在类主体之外,编译器不知道节点是什么,因为我们在类的范围之外。您需要使用类名来限定 node
Octree::node* Octree::search(int dec, int oct)
这允许编译器使用类中的节点
。
在 Octree
中,没有理由在 node
上使用 typedef
。与 C 不同,您在使用 struct
时不必使用 struct
关键字。你可以有
class Octree
{
public:
struct node
{
int value;
node *child[8];
};
//...
};
然后您可以像使用 typedef
一样使用 node
。
关于c++ - 函数返回结构指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36984444/