实现一个C ++后缀增量运算符 [英] implementing a C++ postfix increment operator

查看:161
本文介绍了实现一个C ++后缀增量运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编译了以下示例:

  #include< iostream> 
#include< iterator>
using namespace std;

class myiterator:public iterator< input_iterator_tag,int>
{
int * p;
public:
myiterator(int * x):p(x){}
myiterator(const myiterator& mit):p(mit.p){}
myiterator& operator ++(){++ p; return * this;}
myiterator& operator ++(int){myiterator tmp(* this); operator ++(); return bool operator {return p == rs.p;}
bool operator!=(const myiterator& rhs){return p!= rhs.p ;}
int& operator *(){return * p;}
};

int main(){
int numbers [] = {10,20,30,40,50};
myiterator beginning(numbers);
myiterator end(numbers + 5);
for(myiterator it = beginning; it!= end; it ++)
cout< * it< ;
cout<< endl

return 0;
}

cplusplus.com/reference ,我得到编译器警告:

 code> iterator.cpp:在成员函数'myiterator& myiterator :: operator ++(int)':
iterator.cpp:13:warning:引用局部变量'tmp'返回

这里有什么问题?是后缀签名应该是 myiterator运算符++(int)即返回值?



后缀签名应该看起来像STL迭代器?

解决方案


有什么定义postfix签名应该看起来像STL迭代器?


标准。



决定这样的事情。在这个操作的情况下,标准基本上说你必须返回可转换为 const X& 的地方,其中 X 是迭代器。在实践中,这意味着您可以通过引用返回(如果适用于您)(不会返回)或以值返回。



请参阅24.1.3 / p>

I compiled the following example:

#include <iostream>
#include <iterator>
using namespace std;

class myiterator : public iterator<input_iterator_tag, int>
{
  int* p;
public:
  myiterator(int* x) :p(x) {}
  myiterator(const myiterator& mit) : p(mit.p) {}
  myiterator& operator++() {++p;return *this;}
  myiterator& operator++(int) {myiterator tmp(*this); operator++(); return tmp;}
  bool operator==(const myiterator& rhs) {return p==rhs.p;}
  bool operator!=(const myiterator& rhs) {return p!=rhs.p;}
  int& operator*() {return *p;}
};

int main () {
  int numbers[]={10,20,30,40,50};
  myiterator beginning(numbers);
  myiterator end(numbers+5);
  for (myiterator it=beginning; it!=end; it++)
      cout << *it << " ";
  cout << endl;

  return 0;
}

from cplusplus.com/reference and I get the compiler warning:

iterator.cpp: In member function 'myiterator& myiterator::operator++(int)':
iterator.cpp:13: warning: reference to local variable 'tmp' returned

What's wrong here? Is the postfix signature supposed to be myiterator operator++(int) i.e. return by value?

Is there somewhere defined what the postfix signature should look like on STL iterators?

解决方案

Is there somewhere defined what the postfix signature should look like on STL iterators?

The Standard.

The Standard dictates such things. In the case of this operation, the standard basically says "you have to return something that is convertible to const X&" where X is the iterator. In practice, this means you can return by reference if that applies to you (it doesn't), or return by value.

See 24.1.3/1

这篇关于实现一个C ++后缀增量运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆