Unary operator overhead in C ++

2

I created the next class.

class Persona{

private:
    std::string nombre;

public:
    std::string getNombre();
    Persona operator=(std::string nombre);

};

Persona Persona::operator=(std::string nombre){

    Persona persona;
    persona.nombre = nombre;

    return persona;
}

std::string Persona::getNombre(){
    return this->nombre;
}

As you can see, an operator overload = is done:

Persona operator=(std::string nombre);

What I intend, is to be able to assign the value to the attribute nombre using the operator = .

Leaving my code like this:

#include <iostream>
#include <cstdlib>
#include <string>

class Persona{

private:
    std::string nombre;

public:
    std::string getNombre();
    Persona operator=(std::string nombre);

};

Persona Persona::operator=(std::string nombre){

    Persona persona;
    persona.nombre = nombre;

    return persona;
}

std::string Persona::getNombre(){
    return this->nombre;
}

int main(void)
{

    Persona p;

    p = "John Doe";

    std::cout << "Nombre: " << p.getNombre() << std::endl;

    return EXIT_SUCCESS;
}

When compiling, there is no error, based on what I have read, the operator = makes a return, and this is assigned to the object where it is used:

p = "John Doe";

But! When I run the program, this I get:

  

Name:

     

Process returned 0 (0x0) execution time: 0.015 s

     

Press any key to continue.

The value that should, being assigned, is not assigned, leaving the name empty.

What mistake am I making in operator overload =?

    
asked by Ivan Botero 26.03.2017 в 19:45
source

1 answer

3

The correct thing would be (I show it inline for short):

class Persona{
private:
  std::string nombre;

public:
  Persona &operator=( std::string nnombre ) {
    nombre = nnombre;
    return *this;
  }
};

To access the members of our own class, it is not necessary to precede them with the name of the class; all the members become accessible from the body of the functions, as if they were local variables of the function. It is a facility that offers the language to the programmer.

Therefore, it is not necessary to access them as this->ALGO ; that would be used in case of name conflict; for example, to receive an argument of the method with the same name as an attribute of the class.

In your original code, within operator=( ) , you create a new instance of the class Persona , assign it to that instance, and then return that instance that you created. By doing so, the original instance remains intact .

Notice also that I have changed the return value of your operator= . Instead of returning an instance, I return a reference to the original instance .

    
answered by 26.03.2017 / 19:59
source