我们在写程序的大部分时间都不会去考虑在已有的知识上出现的匮乏,前两天用C++写了一个顺序表,结果却不尽人意,这个或许是因为人生就是这样,在你已知的知识当中出现的知识漏洞你会很难发现,这里还是感谢一下syc大哥,每次在VC驿站上发帖子,他都给我回复了,也就是syc让我更加的喜欢VC驿站。
行了,谈谈出现的错误
这里是我之前出错的代码
http://www.cctry.com/thread-256893-1-1.html
这里我放上了我成功后的代码
SeqList.h
#include<iostream>
#include<stdio.h>
//默认的顺序表大小
const int defaultsize= 10;
//类
template<typename DateType>
class SeqList
{
public:
SeqList(int size = defaultsize)
{
//判断对应的顺序表长度
if (size > 0)
{
maxSize = size;
//数据数组
eml = new DateType[size];
}
}
//析构函数
~SeqList()
{
//申请的数组不为空时进行释放
if (eml != NULL)
{
delete []eml;
eml = NULL;
}
}
int getLength()
{
return curLength;
}
//插入
bool insertElem(DateType e);
//删除
bool delElem(int index);
//查找
DateType findElem(int index);
//更改
bool changeElem(int index, DateType e);
private:
DateType *eml;
int maxSize;
int curLength;
};
//插入
template<class DateType>
bool SeqList<DateType>::insertElem(DateType e)
{
if (curLength < maxSize)
{
eml[curLength] = e;
curLength++;
return true;
}
std::cout << "insertElem function the Array is full" << std::endl;
return false;
}
//删除
template<class DateType>
bool SeqList<DateType>::delElem(int index)
{
if (curLength > index && index >= 0)
{
for (int i = index; i < curLength; i++)
{
eml[i] = eml[i + 1];
}
curLength--;
return true;
}
std::cout << "delElem function wrong index" << std::endl;
return false;
}
//查找
template<class DateType>
DateType SeqList<DateType>::findElem(int index)
{
if (index < 0 && index >= curLength)
{
std::cout << "findElem function wrong index" << std::endl;
return NULL;
}
return eml[index];
}
//更改
template<class DateType>
bool SeqList<DateType>::changeElem(int index, DateType e)
{
if (index >= 0 && index < curLength)
{
eml[index] = e;
return true;
}
std::cout << "changElem function wrong index" << std::endl;
return false;
}
#include "SeqList.h"
#include <iostream>
//success in day 09-01
//模版类的声明和实现必须写在同一个头文件中,否则就无法找到类中对应的函数
int main()
{
//使用泛型类,并调用构造函数
SeqList<int> list(10);
//插入值
for (int i = 0; i < 10; i++)
{
list.insertElem(i);
}
//显示值
for (int i = 0; i < list.getLength(); i++)
{
std::cout << list.findElem(i) << std::endl;
}
//更改值
list.changeElem(3, 5);
list.delElem(4);
//显示值
for (int i = 0; i < list.getLength(); i++)
{
std::cout << list.findElem(i) << std::endl;
}
char a[10];
std::cin >> a;
}下面来源于网上:
在C++标准中没有明确规定,模版类的定义和实现体必须放置到同一个文件中,因为模版类是在预编译期间进行,如果写在两个文件中,增加了编译器的实现难度,所以大多数编译器一般都将模版类的定义和实现放置在同一个文件中。VS2005支持了模版类的分离编写,但是他又检测不出来很多其他的错误,这不得不说还是需要一个天才的大脑来解决这个问题
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/jackhall/article/details/48153033