【发布时间】:2015-04-21 23:48:37
【问题描述】:
我正在执行一项任务,我在其中创建测试代码以显示 C++ 中链表类的实现。大多数提供的所有代码都是从一本书中给出的,而不是我为我的主要功能编写的代码和一些编辑的行来添加一个尾部实例。现在编译时出现的唯一错误是:
'LList::operator=' : must return a value
我不确定为什么会产生这个错误或如何修复它,因为它指的是书中给出的一段代码。那段代码是:
LList& LList::operator=(const LList& source)
{
dealloc();
copy(source);
}
任何帮助将不胜感激。 以防万一;这是我的源文件中的其余代码。
// LList.cpp
#include "LList.h"
#include <iostream>
LList::LList()
{
head_ = NULL;
tail_ = NULL;
size_ = 0;
}
ListNode* LList::_find(size_t position)
{
ListNode *node = head_;
size_t i;
for (i = 0; i<position; i++) {
node = node->link_;
}
return node;
}
ItemType LList::_delete(size_t position)
{
ListNode *node, *dnode;
ItemType item;
if (position == 0) {
dnode = head_;
head_ = head_->link_;
item = dnode->item_;
delete dnode;
}
if (position == size_) {
dnode = tail_;
node = _find(position - 1);
node->link_ = NULL;
tail_ = node;
item = dnode->item_;
delete dnode;
}
else {
node = _find(position - 1);
if (node != NULL) {
dnode = node->link_;
node->link_ = dnode->link_;
item = dnode->item_;
delete dnode;
}
}
size_ -= 1;
return item;
}
void LList::append(ItemType x)
{
ListNode *node, *newNode = new ListNode(x);
if (head_ != NULL) {
node = _find(size_ - 1);
node->link_ = newNode;
tail_ = newNode;
}
else {
head_ = newNode;
tail_ = head_;
}
size_ += 1;
}
void LList::insert(size_t i, ItemType x)
{
ListNode *node;
if (i == 0) {
head_ = new ListNode(x, head_);
tail_ = head_;
}
else if (i == size_) {
tail_ = new ListNode(x, tail_);
}
else {
node = _find(i - 1);
node->link_ = new ListNode(x, node->link_);
}
size_ += 1;
}
void LList::printlist()
{
ListNode *temp = head_;
while (temp) {
std::cout << temp->item_ << std::endl;
temp = temp->link_;
}
}
ItemType LList::pop(int i)
{
if (i == -1) {
i = size_ - 1;
}
return _delete(i);
}
ItemType& LList::operator[](size_t position)
{
ListNode *node;
node = _find(position);
return node->item_;
}
LList::LList(const LList& source)
{
copy(source);
}
void LList::copy(const LList &source)
{
ListNode *snode, *node;
snode = source.head_;
if (snode) {
node = head_ = new ListNode(snode->item_);
snode = snode->link_;
while (snode) {
node->link_ = new ListNode(snode->item_);
node = node->link_;
snode = snode->link_;
}
}
size_ = source.size_;
}
LList& LList::operator=(const LList& source)
{
dealloc();
copy(source);
}
LList::~LList()
{
dealloc();
}
void LList::dealloc()
{
ListNode *node, *dnode;
node = head_;
while (node) {
dnode = node;
node = node->link_;
delete dnode;
}
}
int main()
{
LList mylist;
mylist.append(6);
mylist.append(3);
mylist.append(1);
mylist.printlist();
mylist.insert(2, 4);
mylist.printlist();
mylist.pop(1);
mylist.printlist();
mylist.size();
}
【问题讨论】:
-
你需要买一本不同的书。这段代码很糟糕。
标签: c++ return return-value operator-keyword