顺序表的验证实验代码及常见错误

本文介绍了在C++顺序表验证实验中遇到的编译错误,如错误C2556和C2371,这些问题通常由函数声明和实现的返回类型不一致引起。通过分析代码,指出在Insert函数声明和定义中返回类型的不同是导致错误的主要原因。
Seqlist.h(顺序表验证实验头文件)
#ifndef SeqList_H
#define SeqList_H
const int MaxSize = 10;
class Seqlist
{
public:
	Seqlist(){ length = 0; }
	Seqlist(int a[], int n);
	~Seqlist(){}
	void Insert(int i, int x);
	int	Delete(int i);
	int Locate(int x);
	void PrintList();
private:
	int data[MaxSize];
	int length;
};
#endif
Seqlist.cpp(顺序表验证实验源文件)
#include<iostream>
using namespace std;
#include"Seqlist.h"
Seqlist::Seqlist(int a[], int n)
{
	if (n > MaxSize)throw"参数非法";
	for (int i = 0; i < n; i++)
		data[i] = a[i];
	length = n;

}
void Seqlist::Insert(int i, int x)
{
	if (length >= MaxSize)throw"上溢";
	if (i<1 || i>length + 1)throw "位置非法";
	for (int j = length; j >= i; j--)
		data[j] = data[j - 1];
	data[i - 1] = x;
	length++;
}
int Seqlist::Delete(int i)
{
	if (length == 0)throw"上溢";
	if (i<1 || i>length)throw"位置非法";
	int x = data[i - 1];
	for (int j = i; j < length; j++)
		data[j - 1] = data[j];
	length--;
	return x;

}
int Seqlist::Locate(int x)
{
	for (int i = 0; i < length; i++)
	if (data[i] == x)return i + 1;
	return 0;

}
void  Seqlist::PrintList()
{
	for (int i = 0; i < length; i++)
		cout << data[i] << " ";
	cout << endl;
}
Seqlist_main.cpp(顺序表验证实验主函数部分)
#include <iostream>
using namespace std;
#include "Seqlist.h"
void main()
{
	int r[5] = { 1, 2, 3, 4, 5 };
	Seqlist L(r, 5);
	cout << "执行插入操作前的数据为:" << endl;
	L.PrintList();
	try{
		L.Insert(2, 3);

	}
	catch (char*s)
	{
		cout << s << endl;
	}
	cout << "执行插入操作后数据为:" << endl;
	L.PrintList();
	cout << "值为3元素位置为:";
	cout << L.Locate(3) << endl;
	cout << "执行删除第一个元素操作,删除前数据为:" << endl;
	L.PrintList();
	try{
		L.Delete(1);

	}
	catch (char*s)
	{
		cout << s << endl;

	};
	cout << "删除后的数据为:" << endl;
	L.PrintList();
	system("pause");
}

如果爆出这种错误 :
1>------ 已启动生成: 项目: Seqlist, 配置: Debug Win32 ------
1> Seqlist.cpp
1>d:\c++\visual studio 2013\seqlist\seqlist\seqlist.cpp(13): error C2556: “void Seqlist::Insert(int,int)”: 重载函数与“int Seqlist::Insert(int,int)”只是在返回类型上不同
1> d:\c++\visual studio 2013\seqlist\seqlist\seqlist.h(10) : 参见“Seqlist::Insert”的声明
1>d:\c++\visual studio 2013\seqlist\seqlist\seqlist.cpp(13): error C2371: “Seqlist::Insert”: 重定义;不同的基类型
1> d:\c++\visual studio 2013\seqlist\seqlist\seqlist.h(10) : 参见“Seqlist::Insert”的声明
========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========
可能的原因是把成员函数的声明部分和实现部分的返回值不同导致的,
比如,Insert函数的声明部分为 int Insert (int x,int n);而实现部分为void Insert (int x,int n)就会导致这种错误,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值