您的位置:首页 > 健康 > 美食 > 品牌网上授权_广州网站优化专家_如何免费搭建自己的网站_网络营销师证书有用吗

品牌网上授权_广州网站优化专家_如何免费搭建自己的网站_网络营销师证书有用吗

2025/3/15 0:36:52 来源:https://blog.csdn.net/b405516801/article/details/146239876  浏览:    关键词:品牌网上授权_广州网站优化专家_如何免费搭建自己的网站_网络营销师证书有用吗
品牌网上授权_广州网站优化专家_如何免费搭建自己的网站_网络营销师证书有用吗

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

假设你有一个头文件 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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com