当前位置: 首页 > news >正文

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

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

假设你有一个头文件 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
http://www.dtcms.com/a/67198.html

相关文章:

  • 生成式AI+安全:API防护的“进化革命”——从被动防御到智能对抗的技术跃迁
  • 得物 Android Crash 治理实践
  • Vim忍者速成秘卷:让你的键盘冒出残影の奥义
  • 鸿蒙OS开发ForEach循环渲染
  • qt中再函数中开辟的内存,要不要手动释放?
  • 实现图形界面访问无显示器服务器
  • 【面试】JVM
  • 侯捷C++课程学习笔记:详解多态(五)
  • 【后端】【django drf】django自动导出优雅的api文档的写法
  • easy-poi导出and导入一对多数据excel
  • 基于深度学习的多模态人脸情绪识别研究与实现(视频+图像+语音)
  • mov格式视频如何转换mp4?
  • GESP2024年3月认证C++三级( 第三部分编程题(2)完全平方数)
  • PlainUSR|LIA: 追求更快的卷积网络实现高效的超分辨率重建
  • USB数据采集卡 Labview采集卡 32路AD模拟量采集 DAQ卡
  • 前瞻技术新趋势:改变未来生活方式的技术探索
  • 一个简单的PHP框架
  • 在 Qt 中自定义控件样式:使用 QProxyStyle 代理和修改绘制元素
  • PostgreSQL 部署全攻略:单机与集群模式详解
  • Bash和Zsh的主要差异是?
  • 高效集成销售订单数据到MySQL的方法
  • Unity学习日志番外:简易行为树
  • XML Schema 实例
  • 孔夫子根剧关键字获取在售商品 API
  • iOS开发,SQLite.swift, Missing argument label ‘value:‘ in call问题
  • Docker(认识且会基础操作)
  • LeetCode 解题思路 15(Hot 100)
  • IDEA 一键完成:打包 + 推送 + 部署docker镜像
  • 面试题之webpack file-loader和url-loader
  • 前端面试:cookie 可以实现不同域共享吗?