c++ - 函数返回结构指针

标签 c++ pointers struct

我想用 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/

相关文章:

C++ 函数按值调用的奇怪行为

c++ - 控制台没有输出?

c++ - GlobalAllocPtr() 总是为不同的进程返回相同的地址

c - 使用+检查多个指针是否全为NULL

c - C 中的 strend 函数使用指针?

c - C 中包含结构的数组中的错误值

c++ - 更改窄字符串编码或缺少 std::filesystem::path::imbue

c - 在C函数中返回struct

c - 在结构的 "array"中访问和分配结构的每个部分的值?

c - 段错误(核心转储)在执行 'printf' 语句之前获取打印错误