Fraction class operator overload explanation

I thought a lot (honestly) - from the last semester. And I'm still not quite sure what is happening here. Can anyone help and enlighten me? I'm fine with the pre / postfix difference. It’s damn that the share is increasing, which scares me.

take an example of a prefix, for example. So, if I had a share that was 2/4, would it increase to 3/4? Because when I look at the number + = denomination, it makes me think that it will return 2 + 2 + 4, which is 8.

// prefix increment operator fraction& fraction::operator++() { numer += denom; return *this; } // postfix increment operator fraction fraction::operator++(int) { // Note dummy int argument fraction temp(*this); ++*this; // call the prefix operator return temp; 

thanks for heaps in advance :)

+4
source share
1 answer

The prefix function will point to

 numer = numer + denom; 

therefore, in the case of 2/4 this will be numer = 2 + 4 = 6 , so the result will be 6/4 (since the sign remains unchanged). Since n/n = 1 for all integers (except 0 ), (a+n)/n will always increase by 1 .

The postfix version uses the prefix version to perform the calculation described above.

+3
source

Source: https://habr.com/ru/post/1493600/


All Articles