C++编译问题——1模板函数的实现必须在头文件中

发布于:2025-03-15 ⋅ 阅读:(15) ⋅ 点赞:(0)

今天编译数据结构时,遇见一个编译错误

假设你有一个头文件 SeqList.h 和一个源文件 SeqList.cpp。
SeqList.h

#ifndef SEQLIST_H
#define SEQLIST_H

#include <stdexcept>
#include <iostream>

template<typename T>
class SeqList {
private:
    static const int MAX_SIZE = 100;
    T data[MAX_SIZE];
    int length;
public:
    SeqList();
    void insert(int index, T value);
    // 其他成员函数声明
};

#endif

SeqList.cpp

#include "SeqList.h"

template<typename T>
SeqList<T>::SeqList() : length(0) {}

template<typename T>
void SeqList<T>::insert(int index, T value) {
    if (length >= MAX_SIZE) {
        throw std::overflow_error("List is full");
    }
    if (index < 0 || index > length) {
        throw std::out_of_range("Index out of range");
    }
    for (int i = length; i > index; i--) {
        data[i] = data[i - 1];
    }
    data[index] = value;
    length++;
}

// 其他成员函数实现

main.cpp

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

int main() {
    SeqList<int> list;
    list.insert(0, 10);
    return 0;
}

编译时报如下错误
在这里插入图片描述

解决办法
模板函数的实现必须在头文件中,因为编译器在实例化模板时需要看到完整的实现。所以,你可以直接把 insert 函数的实现放在头文件里。
SeqList.h

#ifndef SEQLIST_H
#define SEQLIST_H

#include <stdexcept>
#include <iostream>

template<typename T>
class SeqList {
private:
    static const int MAX_SIZE = 100;
    T data[MAX_SIZE];
    int length;
public:
    SeqList() : length(0) {}

    void insert(int index, T value) {
        if (length >= MAX_SIZE) {
            throw std::overflow_error("List is full");
        }
        if (index < 0 || index > length) {
            throw std::out_of_range("Index out of range");
        }
        for (int i = length; i > index; i--) {
            data[i] = data[i - 1];
        }
        data[index] = value;
        length++;
    }

    // 其他成员函数声明和实现
};

#endif

网站公告

今日签到

点亮在社区的每一天
去签到