类模板声明与定义(template(class T) class Mycalss {})

在尝试使用C++类模板时遇到LNK1120和LNK2019错误。问题源于类模板的声明与定义不在同一文件。解决方案是将类模板的实现与声明放在一起,以消除链接错误。博客提供了示例代码展示如何正确组织类模板的头文件(test.h)和实现文件(test.cpp)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在看《大化数据结构》的过程中,出现了类模板的定义,由于自己c++编写能力并不是很好,自己写了一个类模板,无论怎么写都出现如下错误:

错误    3    error LNK1120: 2 个无法解析的外部命令    F:\leetcode\Sqlist\Debug\Sqlist.exe    Sqlist
错误    1    error LNK2019: 无法解析的外部符号 "public: __thiscall List<int>::List<int>(int * const,int)" (??0?$List@H@@QAE@QAHH@Z),该符号在函数 _wmain 中被引用    F:\leetcode\Sqlist\Sqlist\Sqlist.obj    Sqlist

但是写一般的类就没问题,搞了半天才知道,类模板的定义与实现最好写在同一个文件中,即声明与实现放到一起,具体为啥减下面的博客:

https://blog.youkuaiyun.com/lichengyu/article/details/6792135

***********************************************************************************************************************

test.h文件:

#ifndef TEST_H
#define TEST_H
#include "stdafx.h"


template <class DataType>
class List{
    public:    
        List(DataType a[], int n);
        //~List();
        bool push(DataType a, int n);
    
    private:
        DataType data[10];
        int len;
};


#endif

***********************************************************************************************************************

test.cpp文件:

tem#include "stdafx.h"
#include "test.h"

plate<class DataType>
List<DataType>::List(DataType a[], int n){
    for (int i = 0; i < n; i++){
        data[i] = a[i];
    }
}

template<class DataType>
bool List<DataType>::push(DataType a, int n){
    data[n] = a;
    return 1;
}

***********************************************************************************************************************

main文件:

#include "stdafx.h"
#include "SeqList.h"
#include "iostream"
#include "test.h"
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    int a[3] = { 1, 2, 3 };
    /*SeqList<int>list(a,3);
    int data;
    list.GetElem(list, 1, &data);
    cout << "data is :" << data << endl*/;
    List<int> list(a,3);
    //List<int> list;
    list.push(0, 3);

    return 0;
}
 

将上述test.cpp中的代码放到test.h中就不会报错了,共勉。
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值