链接列表中的Postincrementation运算符

时间:2014-02-06 07:16:52

标签: c++ linked-list operator-overloading

我必须编写一个处理这个主要代码的程序:(不允许更改它)

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

一切都很好,但只有当我在主程序中评论postincrementation操作时

int ia = iv["john"]++;

正如你所看到的,我有一个struct节点,我把所有变量放在一起,我想在节点中将值增加一,其中键是“john”。有没有办法为这段代码实现operator ++? 我不允许使用std :: map。

2 个答案:

答案 0 :(得分:1)

解决问题的常用方法是将数组下标运算符定义为

const TYPE& operator[](string ind) const;
TYPE& operator[](string ind);

通过这种方式,您不必费心关注operator++:由于iv["John"]会返回对int的引用,iv["John"]++会调用int 1}}内置的后增量运算符。

答案 1 :(得分:0)

是的,我已经尝试过这个解决方案,但编译器不区分读写,仍然使用非const版本。所以我必须构建有助于区分的代理类Cref。 我也已经找到了operator ++问题的解决方案。 此操作必须来自Cref级别。我创建了

Cref& operator++ (int val)
    {
      s.increment(position,val);
      return *this;
    };

在主类体中递增函数如下:

void increment (string ind, int value_)
{
 cout << "increment\n";
 node *t = head;
 while(t)
 {
    if(t->index == ind && t->isInit == true)    t->value = t->value + 1;
    t = t->next;
 }
}  

这完全解决了我的问题。

相关问题