7

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

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

示例代码如下:

节点.h:

#ifndef NODE_H
#define NODE_H
#include <string>

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

#endif

节点.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;
    }

}
4

2 回答 2

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

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

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

}

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

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

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

不需要上课

于 2012-11-20T23:48:46.530 回答
2

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

//node.cpp
#include <string>

using namespace std;

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

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

....
于 2012-11-20T23:50:38.047 回答