C++ 方法的多重定义或 undefined reference

标签 c++ compiler-errors

我用 C++ 创建了一个项目,我需要一些方法在我的类中是虚拟的。所以当我在我的 main.cpp 中包含“类”.h 时,编译器说 undefined reference 我的方法,当我改变“class".h 到 "class".cpp 它说首先在 main.o 中定义,在 class.cpp 中定义多个

class Avl {

public:

    Avlnode* insert(unsigned int key , Avlnode *root);
    AvlofAvlnodes* insert(unsigned int key, unsigned int neighbors[],int size, AvlofAvlnodes *id );

    template <typename nodeptr>
    bool findElement(unsigned int element, nodeptr* root);
    bool findConecion(unsigned int id, unsigned int neighbor,AvlofAvlnodes* root);

    Avlnode* deletion(Avlnode* root,unsigned int key );
    void deletion(unsigned int key , unsigned int neighbor,AvlofAvlnodes* root);

    // methods to help avl
    template <typename nodeptr>
    nodeptr* rightRotate(nodeptr* root);
    template <typename nodeptr>
    nodeptr* leftRotate(nodeptr* root);

    int max(int a,int b);
    template <typename nodeptr>
    int height(nodeptr* root);
    template <typename nodeptr>
    int getBalance(nodeptr* root);
    template <typename nodeptr>
    nodeptr* minValueNode(nodeptr* root);
    template <typename nodeptr>
    void preOrder(nodeptr* node);

};

最佳答案

你总是包含“class.h”,而不是“class.cpp”。这是因为 #include 是在编译阶段处理的,而不同的 .cpp 文件是在链接阶段拼凑在一起的。更准确地说,每个 .cpp 文件都被翻译成一个目标文件,然后将它们链接起来。

您缺少的虚拟方法是缺少目标文件的结果。我们知道 main.cpp 是,但是“class.cpp”是编译的吗?

关于C++ 方法的多重定义或 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50489565/

相关文章:

c++ - 无法在 C++ 中使用 conio 库

asp.net-mvc-4 - 编译asp.net MVC 4 View /在编译时出错,不仅在第一次访问时

C-警告 : control reaches end of non-void function

c++ - 在已经定义运算符C++时不匹配

java - 我是一名初学者编码器,我正在尝试编写井字棋游戏,但出现了我不明白的错误

c++ - Opencv C++ 检测并裁剪图像上的白色区域

c++ - 如何连接二维数据数组

c++ - 创建一个 ostream

c++ - 有什么合理的理由使一元运算符 & 过载?

C++ 重新分配() : invalid pointer