Uses * is this a good idea?

I'm not sure

return *this

Is the only way to return an instance of a class that called a member function? The reason I asked is because our instructor told us to avoid using pointers if necessary, and I wonder if this is the case when the only way to do this is to return that pointer.

I work with a fraction class that contains numerators and denominators of private data. The member function I'm talking about is used to add two fractions, for example:

Fraction C = A.plus(B);

plus a member function is defined as follows:

Fraction& plus( const Fraction frac )

The instructor wants us to do C = A + = B, so I think why.

+3
source share
7 answers

. , () .

  • , , ,
  • , const
  • -

plus(). , .

+7

,

return *this

this , , .

plus , :

Fraction C = A.plus(B).plus(D) // perhaps?

, C . , plus ( A) .

?

Fraction& plus( const Fraction& frac )

, operator= ():

  A& operator=(const A& right) {
    if(this == &right) return *this;    // Handle self-assignment
    b = right.b;
    return *this;
  }

, :

// assuming there a constructor Fraction(int numerator, int denominator):
Fraction* plus(Fraction const& rhs)
{
    return new Fraction(numerator * rhs.denominator
                        + rhs.numerator * denominator,
                        denominator * rhs.denominator);
}

, , , , (?).

:

Fraction plus(Fraction const& rhs)
{
    return Fraction(numerator * rhs.denominator
                    + rhs.numerator * denominator,
                    denominator * rhs.denominator);
}

, .

+2

, . , .

, .

+1

*this. , . , plus - + = , ( , ), *this - .

+1

plus() , , Fraction , , *this. , A A.plus(B). Fraction, plus() :

Fraction plus(const Fraction &frac);

( this plus(), *this?)

0

, , - "" "" , . note: new "" ++:)

// the constructor accepts (numerator, denominator).
// in your case, the caller object would be A, and the called object would be B(other).
return Fraction(numerator * other.denominator + other.numerator * denominator, denominator * other.denominator);

, , - , .

, "",

Fraction plus( const Fraction& frac );

, "".

0

, . .

this. , :

class A {
    public:
    int x;
    int get_x()
    {
        return this->x;
    }

    int get_x_plus_5()
    {
        return this->get_x() + 5;
    }
}

*this.

, , (1) ( , ) (2) , . this .

0

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


All Articles