【问题标题】:C2011 'Node':'class' type redefinitionC2011 'Node':'class' 类型重新定义
【发布时间】:2017-02-18 02:46:12
【问题描述】:

我正在使用 C++ 实现 bptree。我被困在节点创建的初始步骤中。不断收到“C2011 'Node':'class' 类型重新定义”错误。我在网上找到了一些从 cpp 文件中删除类关键字的建议。但是当我删除 class 关键字时,我会收到很多其他错误。这是我的 Node.cpp 代码:

#include "Node.h"
#include <cstdio>
#include <iostream>
#include <string>
#include <map>


using namespace std;


 class Node {
    bool leaf;
    Node** kids;
    map<int, string> value;
    int  keyCount;//number of current keys in the node

    //constructor;
    Node::Node(int order) {
        this->value = {};
        this->kids = new Node *[order + 1];
        this->leaf = true;
        this->keyCount = 0;
        for (int i = 0; i < (order + 1); i++) {
            this->kids[i] = NULL;
        }           
    }
};

Node.h文件如下:

#pragma once
#ifndef NODE_HEADER
#define NODE_HEADER

class Node {

public:
    Node(int order) {};
};

#endif

我该如何解决这个问题?

【问题讨论】:

    标签: c++


    【解决方案1】:

    问题

    在 C++ 中,当您 #include 时,标头会简单地粘贴到正文中。所以现在编译器看到:

    class Node {
    
    public:
       Node(int order) {};
    };
    
    // stuff from system headers omitted for brevity
    
    using namespace std;
    
    class Node {
      bool leaf;
      //...
    };
    

    这里有两个问题:

    1. 编译器看到 class Node 两次具有不同的主体。

    2. Node::Node 定义了两次(第一次为空{})。

    解决方案

    标题应包含类声明

     #include <map>
    
     using namespace std;
    
     class Node {
        bool leaf;
        Node** kids;
        map<int, string> value;
        int keyCount;//number of current keys in the node
    
        //constructor;
        Node(int order);
    };
    

    请注意,构造函数在这里没有主体。这只是一个声明。因为它使用map,所以需要在声明前包含&lt;map&gt;并添加using namespace

    之后不要将class Node 再次放入.cpp.cc 文件中。只将方法实现放在顶层:

    Node::Node(int order) {
      // ...
    }
    

    【讨论】:

    • 感谢您的回复,但是当我删除类节点时,我得到了一堆错误。删除类 Node 后不知道 Node 的任何参数,如 value、kids 等
    • 谢谢,既然我这样做了,我在 Node.h 文件中遇到了错误,上面写着:C2143 syntax error: missing ';'在“ 和 #include
    • 在用map&lt;int, string&gt; value 声明class Node 之前,您是否#include &lt;map&gt;&lt;string&gt;
    • 我忘记在头文件中添加 using namespace std 和在 cpp 文件中添加 main 函数。做了这些,它是没有错误的。非常感谢
    • 你给了我-1吗?真的。你能撤消它吗?这个投票让我无法发布更多问题......
    猜你喜欢
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多