【发布时间】:2014-03-03 00:20:58
【问题描述】:
我必须编写一个程序来处理这个主代码:(不允许更改它)
list<int> iv;
iv["john"] = 23;
int ia = iv["john"]++;
int ib = iv["john"];
cout << ia << " " << ib << endl; // prints 23 24
try{
cout << iv["jack"] << endl; // should throw an exception
}catch(list<int>::Uninitialized&)
{
cout << "Uninitialized map element!" << endl;
};
这是我的代码:
#ifndef EXAM_H
#define EXAM_H
#include <iostream>
#include <string>
using namespace std;
template <class TYPE>
class list
{
private:
struct node
{
TYPE value;
string index;
bool isInit;
node *next;
};
node *head;
node *current;
public:
class Cref
{
friend class list;
list& s;
string position;
Cref (list& ss, string pos): s(ss), position(pos) {};
public:
operator TYPE() const
{
return s.read(position);
}
Cref& operator = (TYPE val)
{
s.write(position,val);
return *this;
};
Cref& operator = (const Cref& ref)
{
return operator= ((TYPE)ref);
};
};
class Uninitialized{};
list ()
{
cout << "constructor\n";
head = NULL;
current = NULL;
}
~list ()
{
while (head)
{
node *t = head->next;
delete head;
head = t;
};
}
TYPE read (string ind) const
{
cout << "read\n";
node *t = head;
while(t)
{
if(t->index == ind && t->isInit == true) return t->value;
else t = t->next;
}
throw Uninitialized();
}
void write (string ind, TYPE value_)
{
cout << "write\n";
node *t = new node;
t->next = head;
head = t;
head->value = value_;
head->index = ind;
head->isInit = true;
}
TYPE operator[] (string ind) const
{
cout << "read\n";
node *t = head;
while(t)
{
if(t->index == ind && t->isInit == true) return t->value;
else t = t->next;
}
throw Uninitialized();
}
Cref operator[] (string ind)
{
return Cref(*this, ind);
}
};
#endif
一切都很好,但只有当我在主程序中注释掉后增量操作时
int ia = iv["john"]++;
如您所见,我有一个结构节点,我在其中放置了所有变量,并且我想在键为“john”的节点中将值递增一。有什么方法可以为此代码实现 operator++ 吗? 我不允许使用 std::map。
【问题讨论】:
-
与问题没有直接关系,但
using namespace std;在全局命名空间中是一个非常糟糕的主意 - 特别是如果您声明自己的名为list的类。 -
如果不对
operator TYPE()操作员的工作方式进行返工,我认为您不会很快解决此问题。正如所写的那样,没有机会增加基础数据,因为没有对它的引用。一切都是 by-val 副本。 -
好的,我明白了。谢谢你。我将使用向量编写另一个版本
标签: c++ linked-list operator-overloading