注册 登录
编程论坛 C++教室

用模块定义的这个链表,类函数不在头文件中为什么不能运行。

gaojiannew 发布于 2013-10-05 22:21, 471 次点击
List.h
#ifndef _LIST_H
#define _LIST_H
template<class T>
class List
{
public:
    void Initial();
    void Show();
protected:
    class Node
    {
        friend class List;
    public:
        Node(T element=0,Node* next=0)
        {
            data=element;
            link=next;
        }
    protected:
        T data;
        Node* link;
    };
    Node* first;
};
#endif
List.cpp
#include"List.h"
#include<iostream>
using namespace std;
template<class T>
void List<T>::Initial()
{
    int m;
    Node* temp;
    cout<<"pls input the num of the list:";
    cin>>m;
    first=new Node(m,0);
    while(1)
    {
        cin>>m;
        if(m==0)
            break;
        first=new Node(m,first);
    }
}
template<class T>
void List<T>::Show()
{
    for(Node* temp=first;temp;temp=temp->link)
        cout<<temp->data<<" ";
    cout<<endl;
}
test.cpp
#include"List.h"
void main()
{
    List<int> A;
    A.Initial();
    A.Show();
   
}

最后测试的结果是:
1>------ 已启动生成: 项目: ConsoleApplication6, 配置: Debug Win32 ------
1>  test.cpp
1>  List.cpp
1>  正在生成代码...
1>test.obj : error LNK2019: 无法解析的外部符号 "public: void __thiscall List<int>::Initial(void)" (?Initial@?$List@H@@QAEXXZ),该符号在函数 _main 中被引用
1>test.obj : error LNK2019: 无法解析的外部符号 "public: void __thiscall List<int>::Show(void)" (?Show@?$List@H@@QAEXXZ),该符号在函数 _main 中被引用
1>C:\Users\Administrator\Documents\Visual Studio 2012\Projects\ConsoleApplication6\Debug\ConsoleApplication6.exe : fatal error LNK1120: 2 个无法解析的外部命令
========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========


2 回复
#2
blueskiner2013-10-06 11:44
类模板需要展开,模板的编译方式,请参照宏。
#3
peach54602013-10-08 14:19
哎...回去再看看书吧...模板的实现要写在h里面,不支持声明...
1