You have the function CopiarLibro()
within public functions, which "binds" the current instance of class Libro
to copy only that book.
To make it more global, you can do the following:
Libro* copiarLibro(Libro *from)
{
Libro *rtn = new Libro(from->titulo, from->autor, /* otros parametros... */);
return rtn;
}
In your code, what you do basically is to define 2 new books, whose value is not yet defined, and you assign a reference NULL
of l2
to l1
, and does not return anything.
As I put it, you define 2 book variables, I used the following class for tests:
class Libro
{
public:
Libro(string);
string Nombre;
};
Libro::Libro(string s)
{
Nombre = s;
}
And the function that I have put you above to copy it:
Libro* copiarLibro(Libro *from)
{
Libro *rtn = new Libro(from->Nombre);
return rtn;
}
This is the main method:
int main()
{
Libro *L1 = new Libro("Historias Chinas del 91");
cout << "Nombre actual de L1: " << L1->Nombre << "\n"; // Imprime: Historias Chinas del 91.
Libro *L2 = copiarLibro(L1);
L1->Nombre = "Cuentos Nacionales"; // Le asigno el valor de otro nombre a L1.
cout << "Nombre de L1: " << L1->Nombre << "\n";
cout << "Nombre de L2: " << L2->Nombre << "\n";
return 0;
}
Showing the following as a result:
Nombre Actual de L1: Historias Chinas del 91
Nombre de L1: Cuentos Nacionales
Nombre de L2: Historias Chinas del 91
Basically, you are going to copy an instance of a book A
in another book B
, to have the same book in 2 different variables.
EDIT: I have not understood exactly what the CopiarLibro()
function is, but since your comment mentions that the function can not have parameters, then I think I understand the function's meaning inside the class.
In that case, use the same function as your class Libro
and add the following to the prototype:
public:
Libro *CopiarLibro(); // El prototipo.
And in its definition:
Libro *Libro::CopiarLibro()
{
Libro *L = new Libro(this->Nombre /* , otros parámetros. */);
return L;
}
And let's try a new method main()
:
int main()
{
Libro *ViejoLibro = new Libro("La biblia");
cout << "El viejo libro: " << ViejoLibro->Nombre << "\n\n";
Libro *NuevoLibro = ViejoLibro->CopiarLibro();
cout << "El nuevo libro:" << NuevoLibro->Nombre << "\n";
ViejoLibro->Nombre = "Vacio"; // Asignamos "vacio" como nombre del libro.
cout << "El viejo libro: " << ViejoLibro->Nombre << "\n";
return 0;
}
Giving the following result:
El viejo libro: La biblia
El nuevo libro:La biblia
El viejo libro: Vacio
I hope it has helped you!