简体   繁体   中英

C++ multiple definition of methods or undefined reference

I make a project to c++ and i need some methods to be virtual in my class.. so When i include in my main.cpp the "class".h , compiler says undefined reference to my method and when i change "class".h to "class".cpp it says first defined in main.o and multiple definition in 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);

};

You always include the "class.h", never the "class.cpp". That's because #include is handled during the compilation phase, while the different .cpp files are pieced together in the linking phase. More accurately, each .cpp file is translated into an object file, and those are then linked.

Your missing virtual methods are the result of a missing object file. We know main.cpp is, but is "class.cpp" compiled?

Only include hpp files and then you need to add the cpp file to the compiler. If you are using the command line, it should look like this:

g++ main.cpp class.cpp -o a.out

If you are using a C++ IDE, it will compile the class.cpp file as long is it is part of your project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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