Why is the second operator function not affecting the variable?
why is the second operator function not affecting itsRadius, thanks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
#include<iostream>
class SimpleCircle
{
public:
SimpleCircle(int radius){*itsRadius=radius;}
~SimpleCircle(){}
int GetItsRadius(){return *itsRadius;}
const SimpleCircle& operator++();
const SimpleCircle& operator++(int);
private:
int *itsRadius = new int;
};
const SimpleCircle& SimpleCircle::operator++()
{
++*itsRadius;
return *this;
}
const SimpleCircle& SimpleCircle::operator++(int x)
{
*itsRadius++;
return *this;
}
int main()
{
SimpleCircle ACircle(5);
std::cout<<"Its radius = " <<ACircle.GetItsRadius()<< std::endl;
++ACircle;
std::cout<<"Its radius = " <<ACircle.GetItsRadius()<< std::endl;
ACircle++;
std::cout<<"Its radius = " <<ACircle.GetItsRadius()<< std::endl;
}
|
Last edited on
Because you're calling ++ on a pointer, not on the thing being pointed at.
1 2 3 4 5
|
const SimpleCircle& SimpleCircle::operator++(int x)
{
(*itsRadius)++;
return *this;
}
|
Why is the radius accessed through a pointer at all?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
#include<iostream>
class SimpleCircle
{
public:
explicit SimpleCircle( int radius ) { if( radius > 0 ) itsRadius = radius; }
int Radius() const { return itsRadius; }
SimpleCircle& operator++() { ++itsRadius ; return *this ; }
SimpleCircle operator++(int) { auto old_value = *this ; ++*this ; return old_value ; }
private: int itsRadius = 1 ;
};
int main()
{
SimpleCircle ACircle(5);
std::cout << "Its radius = " << ACircle.Radius() << '\n'; // 5
std::cout << "Its radius = " << (++ACircle).Radius() << '\n'; // 6
std::cout << "Its radius = " << (ACircle++).Radius() << '\n'; // 6 (old value before increment)
std::cout << "Its radius = " << ACircle.Radius() << '\n'; // 7
}
|
Topic archived. No new replies allowed.