C++ 头文件和源文件之间的“类类型重定义”错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13484178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:22:40  来源:igfitidea点击:

"Class type redefinition" error between header and source files

c++visual-studio-2010visual-studio

提问by trevwilson

So I'm having a problem which I'm sure there is an extremely obvious solution for, but I just can't seem to figure it out. Basically, when I try to do class definitions in my headers and implementation in my source files, I am getting an error saying that I am redefining my classes. Using Visual C++ 2010 Express.

所以我遇到了一个问题,我确信有一个非常明显的解决方案,但我似乎无法弄清楚。基本上,当我尝试在我的头文件中进行类定义并在我的源文件中进行实现时,我收到一条错误消息,提示我正在重新定义我的类。使用 Visual C++ 2010 Express。

Exact error: "error C2011: 'Node' : 'class' type redefinition"

确切错误:“错误 C2011:‘节点’:‘类’类型重新定义”

Example code included below:

示例代码包含在下面:

Node.h:

节点.h:

#ifndef NODE_H
#define NODE_H
#include <string>

class Node{
public:
    Node();
    Node* getLC();
    Node* getRC();
private:
    Node* leftChild;
    Node* rightChild;
};

#endif

Node.cpp:

节点.cpp:

#include "Node.h"
#include <string>

using namespace std;


class Node{
    Node::Node(){
        leftChild = NULL;
        rightChild = NULL;
    }

    Node* Node::getLC(){
        return leftChild;
    }

    Node* Node::getRC(){
        return rightChild;
    }

}

回答by Syntactic Fructose

class Node{
    Node::Node(){
        leftChild = NULL;
        rightChild = NULL;
    }

    Node* Node::getLC(){
        return leftChild;
    }

    Node* Node::getRC(){
        return rightChild;
    }

}

you declare the class twice in your code, the second time being in your .cpp file. In order to write the functions for your class you would do the following

您在代码中两次声明该类,第二次是在 .cpp 文件中。为了为您的类编写函数,您将执行以下操作

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

void Node::FunctionName(Type Params)
{
    //...
}

no class is required

不需要上课

回答by jpumford

You're redefining the Node class, as it is saying. The .cpp file is just for the implementation of the functions.

正如它所说,您正在重新定义 Node 类。.cpp 文件仅用于功能的实现。

//node.cpp
#include <string>

using namespace std;

Node::Node() {
  //defined here
}

Node* Node::getLC() {
  //defined here
}

....