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 =?