class Point{
private:
int xpos, ypos;
public:
Point(int x=0, int y=0) : xpos(x), ypos(y) { }
void showPosition() const {
cout<<"["<<xpos<<", "<<ypos<<"]"<<endl;
}
Point& operator++(){ //Point operator++()
xpos+=1;
ypos+=1;
return *this;
}
};
For operator++() I know Point& is the right return type, but I don't get why Point return type would not also work.
Point operator++(){
xpos+=1;
ypos+=1;
return *this;
}
when I use this to perform
Point pos(1,3);
++(++pos);
I get
[2,4]
not
[3,5] //which is what I should be getting.
I think operator++() without the reference should still give the same result, as it would implicitly call its copy constructor, so albeit slower, I think it should give the same result.
When ++
returns a copy, then the second ++
in ++(++pos)
calls operator++
on the copy returned by the first ++
, not on the original pos
. Thus the original pos
is only incremented once.
Point& operator++()
should return by reference to non-const so as to let us do ,
Point p;
++++p;
Had it returned Point
, you would be trying to modify the temporary which is not the behavior you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.