【问题标题】:template and operator overloading and iterator模板和运算符重载和迭代器
【发布时间】:2016-02-03 09:39:36
【问题描述】:

我被要求写一个与istream_iterator功能相同的迭代器,迭代器的名字是CMyistream_iterator。我想设置 * 运算符的功能,因为它在迭代器中使用。

  template<class T>
    class CMyistream_iterator{
        public:
        T my;
        T* cm;
        CMyistream_iterator(istream& x):my(x){};
        T operator * (CMyistream_iterator<T>& p);
    };
    template<class T>
    T CMyistream_iterator<T>::operator * (CMyistream_iterator<T>& p){return p.my;}
    int main()
    {
        CMyistream_iterator<int> inputInt(cin);
        int n1,n2,n3;
        n1 = * inputInt;
    }

但代码出错并说“'operator*' 不匹配(操作数类型为 CMyistream)”。谁能帮帮我?

【问题讨论】:

    标签: c++ templates iterator operator-overloading


    【解决方案1】:

    您的问题与模板无关,而与运算符重载的基础有关。你需要写简单

    T operator * ();
    

    T CMyistream_iterator<T>::operator * (){
        return my; // meaning this->my
    }
    

    原因是您的操作员已经是班级成员,他们已经拥有 一个隐式参数——类对象本身,这是您需要使用的参数。

    您编写的代码声明的不是间接运算符 (*x),而是乘法运算符 (x*y)。

    您的代码中的另一个问题是您试图将CMyistream_iterator(istream&amp; x):my(x){}; 中的istream 转换为int,但这与您提到的编译错误无关;这个问题的解决方案取决于你到底需要做什么。

    【讨论】:

      猜你喜欢
      • 2011-10-18
      • 2013-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-03
      • 2020-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多