问题记录
模板类不支持声明(.h)和实现(.cpp)分开写
正确写法
在.h文件中将方法全部实现
#ifndef LINEARLIST_H
#define LINEARLIST_H
#include <iostream>
using namespace std;
template <class T>
class LinearList {
public:
LinearList() {
maxSize = 1;
element = new T[maxSize];
length = 0;
}
LinearList(int maxListSize) {
maxSize = maxListSize;
element = new T[maxSize];
length = 0;
}
bool isEmpty() {
return length != 0;
}
int getLength() {
return length;
}
//返回第k个元素至x中
bool toFind(int k, T &x) const {
if(k > maxSize || k < 0 || k < length) {
cout << "k is illegal" << endl;
return false;
}
x = element[k - 1];
return true;
}
// 返回x所在位置
int toSearch(const T& x) const {
for (int i = 0; i < length; i ++) {
if(element[i] == x) {
return ++ i;
}
}
return 0;
}
// 删除第k个元素并将它返回至x中
LinearList<T>& Delete(int k, T& x) {
if(toFind(k, x)) {
for(int i = k; i < length; i ++) {
element[i - 1] = element[i];
}
length = length - 1;
return *this;
}
}
// 在第k个元素之后插入x
LinearList<T>& Insert(int k, const T& x) {
if(k < 0 || k > length) {
cout << "k is illegal" << endl;
}
if(k > maxSize) {
cout << "out of memory" << endl;
}
for (int i = length - 1; i >= k; i--) {
element[i + 1] = element[i];
}
element[k] = x;
length ++;
return *this;
}
// 反序
void Reverse() {
int low = 0;
int high = length - 1;
while(high > low) {
swapElement(element[high], element[low]);
high --;
low ++;
}
}
void swapElement(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
friend ostream& operator<< (ostream& out, LinearList& linearList) {
for(int i = 0; i < linearList.getLength(); i ++) {
out << "LinearList.element " << endl;
out << linearList.element[i];
}
return out;
}
virtual ~LinearList() {
delete []element;
}
protected:
private:
int length;
int maxSize;
T *element;
};
#endif // LINEARLIST_H
main中调用
#include <iostream>
#include "Person.h"
#include "LinearList.h"
#include "Sort.h"
using namespace std;
int main()
{
Person me;
me.setPersonName("me");
me.setPersonAge(22);
me.setPersonGender("female");
me.setPersonWeight(50.0f);
Person personDao("personDao", 23, "female", 50.0f);
Person personQiang("personQiang", 23, "female", 40.0f);
Person personPao("personPao", 22, "female", 50.0f);
Person personDun("personDun", 22, "female", 50.0f);
LinearList<Person> listPerson;
listPerson.Insert(0, me);
listPerson.Insert(1, personDao);
listPerson.Insert(2, personQiang);
listPerson.Insert(3, personPao);
listPerson.Insert(4, personDun);
cout << listPerson << endl;
listPerson.Reverse();
cout << listPerson;
return 0;
}