I want to define the link list method using a template.

Asked 1 years ago, Updated 1 years ago, 309 views

I would like to define the link list method using the template.I made a code like the one below, but a problem.If you define addHead() in the source file (cpp file), you cannot compile it properly.However, defining the exact same thing in the header file (h file) will allow you to compile it successfully.
Also, if you define it in the source file, you get the following error:

error LNK2019: Unresolved external symbol "public:void__thiscallList<int>::addHead(int)" (?addHead@?$List@H@@QAEXH@Z) referenced in function_main
lab9.exe: fatal error LNK1120: 1 unresolved external reference

My idea is that the Link class is not well referenced in List.cpp, but there is no basis.
I would like to define the link list method in the source file somehow, so please give me some advice.
Note: I coded using CLion.

main.cpp

#include<iostream>
# include "List.h"

using namespace std;

int main() {

    int size = 5;
    List <int > numbers;
    for (inti=0; i<size;i++)
    {
        numbers.addHead(i);
    }

    cout<<number.showList();
    return 0;
}

List.h

#include<string>

using std::string;


template<typename T>
class Link
{
private:
    T value;
    Link*next;
public:
    // constructor
    Link(T value, Link*next=nullptr): value(value), next(next){}
    // destructor
    virtual~Link(){}
    // return value
    T getValue() {return this ->value;}
    // return next
    Link*getNext() {return this ->next;}
    // set next
    void setNext(Link*next) {this->next=next;}
};

template<typename T>
class list
{
private:
    Link <T>*head;
public:
    List():head(nullptr){}
    // virtual to List();
    void addHead(T value);

    // for testing
    
    US>string showList()
    {
        US>//#string buffer=";
        if(head==nullptr)
        {
            buffer = "Nothing in the List";
        }
        else
        {
            buffer="Head->";
            for (Link<T>*currentLink=head;currentLink;currentLink=currentLink->getNext())
            {
                buffer+=std::to_string(currentLink->getValue());
                buffer+="->";
            }
            buffer+="nullptr";
        }
        return buffer;
    }
    
};

List.cpp

#include "List.h"


template<typename T>
void List<T>::addHead(T value)
{
    Link<T>*theLink;
    theLink = new Link <T>(value);
    theLink ->setNext(head);
    head=theLink;
}

c++

2022-09-30 21:56

1 Answers

As you can imagine, "List.cpp" is not compiled or linked.

·The solution depends on the environment in which it is built, so if you add it, you can expect a more appropriate answer.

An example is an overview of additional steps when using Visual Studio.

Let's "rebuild" it once we've confirmed it.


2022-09-30 21:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.