简体   繁体   English

为什么我不断收到 Class 错误的重新定义? C++

[英]Why do I keep getting Redefinition of Class Error? C++

I keep getting the error: "Redefinition of 'CBSTree'" and "Previous definition is here" on all my functions in my cbstree.cpp code.我在我的 cbstree.cpp 代码中的所有函数上不断收到错误消息:“重新定义'CBSTree'”和“以前的定义在这里”。 I'm not sure why.我不确定为什么。 I believe I have the correct include guards and such.我相信我有正确的包括警卫等。 Help would be very much appreciated.帮助将不胜感激。 Thank you.谢谢你。

main.cpp主文件

#include    <iostream>
#include    <cstdlib>
using namespace std;
#include    "cbstree.h"

// define to show duplicate insertions
#define SHOW_INSERT

// defined constants
const   int         BUFLEN = 256;

cbstree.cpp cbstree.cpp

#include    <fstream>
#include    <iostream>
#include    <cstdlib>
using namespace std;
#include    "cbstree.h"

template    <typename  NodeType>
CBSTree<NodeType>::CBSTree(const CBSTree<NodeType>  &other)
{
    m_root = NULL;
    if(m_root != other.m_root)
    {
        DestroyTree();
        m_root = CopyTree(other.m_root);
    }
}  // end of "CBSTree<NodeType>::CBSTree"

cbstree.h cbstree.h

#ifndef CBIN_SEARCH_TREE_HEADER
#define CBIN_SEARCH_TREE_HEADER

#include    "ctreenode.h"

// class declaration
template    <typename  NodeType>
class   CBSTree
{
public:
    // constructors and destructor
    CBSTree() : m_root(NULL) {}
    CBSTree(const CBSTree  &other);
    virtual ~CBSTree() { DestroyTree(); }
...

#include    "cbstree.cpp"
#endif  // CBIN_SEARCH_TREE_HEADER

ctreenode.h ctreenode.h

#ifndef CTREE_NODE_HEADER
#define CTREE_NODE_HEADER

#include    <iostream>
using namespace std;

template    <typename NodeValueType>
class   CTreeNode
...

#endif  // CTREE_NODE_HEADER

If you include the definition into more than one cpp file you get redefinitions.如果将定义包含在多个 cpp 文件中,则会得到重新定义。

And you do so with both lines #include "cbstree.h" .并且您使用这两行#include "cbstree.h"执行此操作。
(This answer ignores that you indirectly include the cbstree.cpp into itself; though that might be a shortcoming of your inconsistent MRE.) (此答案忽略了您将 cbstree.cpp 间接包含在其自身中;尽管这可能是您不一致的 MRE 的缺点。)

As churill mentioned, including cpp files will sooner or later get you into trouble.正如 churill 所说,包含 cpp 文件迟早会给您带来麻烦。
Learn about the goals of headers and code files please.请了解标头和代码文件的目标。 There are Q/As here on that.这里有 Q/As。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM