Overload of c++ operators

Asked

Viewed 83 times

1

Greetings! I need to implement this Feetinches class method.

FeetInches operator - (const FeetInches &);

I’m wondering if it makes sense for the parameter not to have a name, just the type. If so, how do I use it. Hugs.

  • Luana, see the @Maniero answer in this question https://answall.com/questions/136279/qual-a-difference-declaration-e-definition/136280#136280. The instruction presented in your question is a statement of the operator '-', i.e, the introduction of an identifier and its properties. In this case, you are simply informing the compiler of the existence of this identifier and its characteristics (it receives a Feetinches reference and returns an object of type Feetinches), so it is not necessary to specify the parameter name.

1 answer

0

You are confusing statement with implementation. This is specifically applied to methods or functions.

Imagine you need a function that adds two integers. In this case you can somewhere declare the function by omitting the parameter name:

int soma(int, int);

The previous line of code indicates that there is a sum function that returns an integer and takes two integers as parameter, but whose implementation will still appear.

Later you can implement the function, giving you the code needed to do what you want, and in the implementation the names of the parameters already have to be indicated:

int soma(int operando1, int operando2){
    return operando1 + operando2;
}

But note that depending on the situation, you may not want to declare the function beforehand and only write its implementation. There are scenarios where you really need to declare beforehand, but most of them don’t.

In his example only has the statement, and so it is not necessary to have the name. But in order to compile correctly you will need the implementation that includes the code of the method itself. Making the statement and then having the implementation in the class does not bring you much advantage so I suggest just putting the implementation, something like:

class FeetInches {
    ... //outros campos e métodos da classe

    FeetInches operator-(const FeetInches &param1){
        ... //codigo que interpreta o param1 e faz a negação/inversão
        return ...; //retornar a nova instância após a operação
    }
};

Note: all the ... represent the specific code of its implementation, related to its objective.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.