【发布时间】:2021-04-20 01:08:51
【问题描述】:
所以我有一个自己的链表实现,它可以成功地保留整数并在需要时使用重载的 [] 运算符调用它们,但是在我的链表中存储一个类时,我似乎无法调用适当的类(使用相同的 [] 运算符)。 被调用的函数和我的链接列表的成员;
#include <iostream>
#include <assert.h>
template<typename T>
struct node {
T data;
node<T>* next;
};
template<typename T>
class Vectem {
private:
node<T>* head;
node<T>* last;
int lenght;
public:
void insert(T value) {
last->next = new node<T>;
last = last->next;
last->data = value;
last->next = NULL;
if (isEmpty()) {
head = last;
}
lenght++;
}
node<T>* search(int indx) {
node<T>* current;
current = head;
int count=0;
while (current != NULL) {
if (count == indx) {
break;
}
current = current->next;
count++;
}
return current;
}
T& operator [](int indx) {
assert(indx >= lenght - 1);
T result;
result = search(indx)->data;
return result;
}
};
这是我尝试存储的主要功能和类;
#include <iostream>
#include <fstream>
#include <string>
#include "VectemLibrary.h"
class word {
public:
std::string value;
int count;
word(std::string value, int count): value(value),count(count) {
}
word() {
value = "NOT ASSIGNED";
count = 0;
}
word(const word& w1) {
value = w1.value;
count = w1.count;
}
~word() {
std::cout << "Word Destroyed" << std::endl;
}
};
int main()
{
Vectem<word> wordContainer;
word newWord("hello", 1);
wordContainer.insert(newWord);
std::cout << wordContainer[0].value;
}
Visual Studio 在最后一行给了我这个消息的期望,我用[] 调用链表的第一个成员;
在 Top 10 words.exe 中的 0x7A0CF3BE (ucrtbased.dll) 处引发异常:0xC0000005:访问冲突读取位置 0xCCCCCCCC。
我认为我缺乏指针经验可能会导致问题,但是如果您看到我看不到的东西,请赐教。
【问题讨论】:
-
T result; ...return result;您正在返回对局部变量的引用。试试return search(indx)->data; -
另外,在
insert()中有last->next = new node<T>;。但是第一次调用这个函数时last的值是多少?
标签: c++ class linked-list