【发布时间】:2017-09-17 18:00:43
【问题描述】:
我有以下数据结构课程的家庭作业。
使用指针数组设计和实现有序列表类。这个类应该是一个模板。 该模板预计会重载
>、<和==运算符。
- 该类应该有一个包含 20 个项目的数组。
- 在搜索插入新项目的位置时,
AddItem方法应从数组的前面开始。RemoveItem方法应确保数组中的项目仍然有序且项目之间没有空白点。- 该类应包括
IsEmpty、IsFull和MakeEmpty方法。
我有一个有序列表类的工作实现,但分配说我的模板类应该重载一些比较运算符,我不知道为什么我需要这样做。我已阅读 What are the basic rules and idioms for operator overloading?,但不知道如何在此处应用。
这是我目前的解决方案:
#include <cstddef>
#include <iostream>
using namespace std;
#define LEN 20
template <class T> class orderedList
{
protected:
T *arr[LEN] = {}; // Array of pointers
public:
void addItem(T item);
void removeItem(T item);
bool isEmpty();
bool isFull();
void makeEmpty();
bool operator<(const T& rhs) const;
bool operator>(const T& rhs) const;
bool operator==(const T& rhs) const;
};
// Overloaded comparison operators
template <class T> bool orderedList<T>::operator<(const T& rhs) const {
return this < rhs;
}
template <class T> bool orderedList<T>::operator>(const T& rhs) const {
return rhs < this;
}
template <class T> bool orderedList<T>::operator==(const T& rhs) const {
return this == rhs;
}
template <class T> void orderedList<T>::addItem(T item)
{
T temp1 = item;
T temp2;
for (int i=0; i<LEN; i++) {
if(arr[i] == NULL) {
arr[i] = new T;
*arr[i] = temp1;
return;
} else if (*arr[i] > item) {
temp2 = *arr[i];
*arr[i] = temp1;
temp1 = temp2;
} else {
continue;
}
}
cout << "full error!" << endl;
}
template <class T> void orderedList<T>::removeItem(T item)
{
int cur = 0;
while( cur<LEN && arr[cur] != NULL && item > *arr[cur]) {
cur++;
}
if (*arr[cur] == item) {
while(cur+1<LEN && arr[cur+1] != NULL) {
*arr[cur] = *arr[cur+1];
cur++;
}
delete arr[cur];
arr[cur] = NULL;
} else {
cout << "not found error!" << endl;
}
}
template <class T> bool orderedList<T>::isEmpty()
{
for(int i=0; i<LEN; i++) {
if (arr[i] != NULL)
return false;
}
return true;
}
template <class T> bool orderedList<T>::isFull()
{
// Traverse in reverse for speed
for(int i=LEN-1; i>0; i--) {
if (arr[i] == NULL)
return false;
}
return true;
}
template <class T> void orderedList<T>::makeEmpty()
{
for(int i=0; i<LEN; i++) {
if (arr[i] != NULL) {
delete arr[i];
arr[i] = NULL;
}
}
}
这似乎有效,但是重载的比较运算符没有做任何特别的事情,我也看不出他们需要这样做的任何理由。我最好的猜测是我应该尝试在比较运算符中包含对 NULL 的检查,但我不确定这是否可能。
【问题讨论】:
-
StackOverflow 不会为你做作业。
-
在使用 c++ 编程时,您不希望有像 指针数组 这样的东西。没必要这样。
-
谢谢,@Charles。我只是想了解为什么我需要在这里重载运算符。我已阅读 meta.stackoverflow.com/questions/334822/… 并相信我遵循了所有准则。我真诚地努力解决问题,我提出了一个关于我的实施的具体问题,并明确地将其确定为家庭作业。
-
@user0042 我无法改变它。这是给定的任务,所以:耸耸肩:。
-
我不明白您为什么要将
orderedList<T>与T类型的东西进行比较。
标签: c++ pointers operator-overloading