Está en la página 1de 41

UCSM Esc. Prof.

de Ingeniería de INFORME DE PRÁCTICAS


Sistemas

ABRIL- 2021 LENGUAJES DE


PROGRAMACIÓN II

Práctica N° 08
Elaborado por:
- Nombre y Código
- Maria Fernanda Huarcaya Quispe 2020243642
- Carlos Elisban Huaman Quispe 2020243481
- Bryan Carlos Tarqui Gomez 2017826151

© IEEE 2013 The Institute of Electrical and Electronics Engineers, Inc.


Práctica N° 1: XXXXXXXXXXX

ii
GRUPO N° 2

PRÁCTICAS DE LENGUAJES DE PROGRAMACIÓN II

Presentado por:

- Nombre y Código
- Maria Fernanda Huarcaya Quispe 20203642
- Carlos Elisban Huaman Quispe 2020243481
- Bryan Carlos Tarqui Gomez 2017826151
RECONOCIMIENTOS

El autor de este trabajo reconoce con gratitud a los creadores de los lenguajes C, C++ y
otras personalidades y autores de libros de programación Bjarne Stroustrup, Dennis
Ritchie, Herb Sutter, Herb Sutter, James Gosling, James Gosling, Brian Kernighan, Brian
Kernighan, Ken Thompson.

PALABRAS CLAVES

Plantilla, Clases, Metodos, Funciones


ÍNDICE

1. RESUMEN …………………………………………………………………………………………………….7
2.
2. INTRODUCCIÓN................................................................................................................................ 7
3. MARCO TEÓRICO............................................................................................................................. 8
3.1 Plantillas.................................................................................................................................... 8
3.1.1 Plantillas en funciones…………………………………………………………………………..9
3.1.2 Plantillas en clases……………………………………………………………………………..10
3.2 Clases en C++…………………………………………………………………………………………11
4. MODELAMIENTO............................................................................................................................ 12
4.1 Diagrama de clases del proyecto...............................................................................................12
5. EXPERIENCIAS DE PRÁCTICA......................................................................................................13
5.1 Externo……………………………………………………………………………………………………13
5.2 Interno…………………………………………………………………………………………………….32
6. CONCLUSIONES DE LA PRÁCTICA:..............................................................................................40
7. CUESTIONARIO.............................................................................................................................. 40
8. BIBLIOGRAFÍA................................................................................................................................. 40
Práctica N° 9: Manejo de Excepciones

1. RESÚMEN
En esta sesión se tocara lo que son las plantillas de función con las cuales podemos tomar la
plantilla de función como una función especial, en la que el tipo de parámetro puede ser de
cualquier tipo, de esta forma podemos reducir las definiciones repetidas, de modo que la
plantilla de función se pueda adaptar automáticamente a diferentes tipos de parámetros, es
decir, la función se pueda adaptar a múltiples tipos de parámetros, como double, int y mas.

2. INTRODUCCIÓN
Las plantillas de funciones son funciones especiales que pueden operar con tipos genéricos. Esto
nos permite crear una plantilla de función cuya funcionalidad se puede adaptar a más de un tipo
o clase sin repetir todo el código para cada tipo.
En C ++, esto se puede lograr utilizando parámetros de plantilla. Un parámetro de plantilla es un
tipo especial de parámetro que se puede utilizar para pasar un tipo como argumento: al igual
que los parámetros de una función normal se pueden utilizar para pasar valores a una función,
los parámetros de plantilla permiten pasar también tipos a una función. Estas plantillas de
funciones pueden utilizar estos parámetros como si fueran cualquier otro tipo normal.
Una platilla es una herramienta simple pero muy poderosa en C++. La idea simple es pasar el tipo
de datos como un parámetro para que no necesitemos escribir el mismo código para diferentes
tipos de datos. Por ejemplo, una empresa de software puede necesitar ordenar() para diferentes
tipos de datos. En lugar de escribir y mantener varios códigos podemos escribir un ordenar() y
pasar el tipo de datos como parámetros.
C++ agrega dos palabras claves nuevas para admitir plantillas: “platilla” y “nombre de tipo”. La
segunda palabra clave siempre se puede remplazar por la palabra clave “clase”.
o

7
Práctica N° 8: Plantillas de Función y Clase en C++

3. MARCO TEÓRICO
3.1 Plantillas
¿QUÉ ¿CÓMO SE DECLARA? ¿CÓMO FUNCIONA? ¿CUÁNDO LO USO?
ES?

Las plantillas también son Se declara una plantilla con la Este se expande en el momento del Lo usamos en la programación
conocidas como funciones o palabra clave para la sintaxis de la compilador. La diferencia que se genérica.
clases genéricas. Una plantilla y los corchetes angulares encuentra es que el compilador realiza
plantilla es un plan o en un parámetro (t), que define la la verificación de tipos antes de la
fórmula para crear una clase variable de tipo de datos. [1] expansión de la plantilla. Con la idea
o función genérica.[1] de que el código fuente contiene solo
función / clase, pero el código
De forma sencilla, puede compilado puede contener múltiples
crear una sola función o copias de la misma función / clase. [1]
clase para trabajar con
diferentes tipos de datos
utilizando plantillas. [1]

1
3.2.1 Plantillas Funciones
¿QUÉ ¿CÓMO SE DECLARA? ¿CÓMO FUNCIONA? ¿CUÁNDO LO USO?
ES?
Nos muestra la suma de A+B
Las plantillas de función son Una plantilla de función se Template<typename T> Las plantillas se instancian en
parecidas a una función que declara con la palabra clave T Sum( T N1, T N2){ // Plantilla tiempo de compilación con el
se utiliza para poder generar Template seguida de la plantilla función código fuente. [2]
una o más funcionesde parametros dentro de <>. T X;
sobrecargadas, ya que cada X = N1+N2; Las plantillas se usan menos
uno con un conjunto diferente La palabra clave de tipo de return X; código que las funciones
de tipo reales. Permitiendo plantilla especificada puede ser } sobrecargadas.
poder crear funciones que “class” o “typename[2] Int main(){
puedan funcionar con muchos int A = 10, B= 20,C; Las plantillas permiten
tipos diferentes. [2] C = Sum(A+B); //Llama la parametros que no son de tipo.
plantilla función [2]
Cuando creamos nuestra Cout << “\n La suma de A+ B es:
plantilla de función, usamos “ <<C;
tipos de marcador de posición }
(también llamados tipos de
plantilla) para cualquier tipo
de parámetro, tipo de retorno
o tipo usado en el cuerpo de
la función que queremos que
se especifique más adelante.
[2]

1
3.2.2 Plantillas en clase
¿QUÉ ¿CÓMO SE DECLARA? ¿CÓMO FUNCIONA? ¿CUÁNDO LO USO?
ES?

Al igual que las plantillas de Una plantilla en clase como dice Nos muestra la suma de A+B Lo usamos para crear una clase
funciones, también puede su nombre se declara en una clase Template<class T> diferente para cada tipo de datos
crear plantillas de clases la palabra clave Template seguida Class suma{// Plantilla función O crear diferentes variables
para operaciones de clases de la plantilla de parametros Public: miembro y funciones dentro de
genéricas. [3] dentro de <>. T add(T,T); una sola clase. [3]
};
A veces, necesita una Template<class T>
implementación de clase T suma <T>::Add (T N1, T N2){
que sea la misma para todas T X;
las clases, solo los tipos de X = N1+N2;
datos utilizados son return X;
diferentes. [3] }
Int main(){
Sin embargo, las plantillas Suma<int>obj1;
de clase facilitan la int A = 10, B= 20,C;
reutilización del mismo C = Sum(A+B); //Llama la
código para todos los tipos plantilla función
de datos. [3] Cout << “\n La suma de A+ B es:
“ <<C;
}

1
3.2 Clases en C++
¿QUÉ ¿CÓMO SE DECLARA? ¿CÓMO LO ¿CUÁNDO LO USO?
ES? USO?

Es un tipo de datos definido La clase se declara con la palabra Sintaxis Una clase se usa cuando se
por el usuario que tiene sus clave que es Class [4] #include <iostream> quiere especificar la forma de un
propios miembros de datos Class (Palabra clave) Cclase (nombre objeto y combina la
y funciones. Estos se definido por el usuario) representación de datos y los
pueden acceder y usar { métodos para poder manipular
creando una instancia de esa Acceso especificado: eso datos de manera ordenado.
clase. [4] Privados, públicos y protegidos [4]
Miembros de datos:
La clase en C++ es como el Variables Si desea definir un mismo tipo
plano de un objeto. Miembros de funciones () de variable con muchas
No define ningún modelo Miembros de acceso de datos de propiedades, puede usar clases.
para un tipo de datos, define …miembros [4]
lo que sígnica el nombre }
definido por el usuario, en // Cuerpo de función
que consiste un objeto de Terminación de clases con punto y
clases y que operaciones se coma.
realiza en dicho objeto. [4]

1
Práctica N° 8: Plantillas de Función y Clase en C++

4. MODELAMIENTO
4.1 Diagrama de clases proyecto

1
2
Práctica N° 8: Plantillas de Función y Clase en C++

5. EXPERIENCIAS DE PRÁCTICA
5.1 Proyecto
----------------------------------| Externo |------------------------------------
#include<iostream>
#include<stdlib.h>
using namespace std;
class List;
class Username{
private:
string name;
string gender;
int age;
public:
Username();
Username(string,string,int);
void setregister(string,string,int);
void show_data();
~Username();
//metodo virtual
virtual void look_list();
};

class Student : public Username{


private:
static int numberStudent;
string student_code;
string grade;
string section;
public:
Student();
Student(string);
Student(string,string,string);

1
3
Práctica N° 8: Plantillas de Función y Clase en C++

Student(string,string,int,string,string,string);
void study();
int getnumberStudent(){
return numberStudent;
}
static int dividir2(){
int M2=numberStudent/2;
return M2;
}
static int dividir4(){
int M4=numberStudent/4;
return M4;
}
static int dividir6(){
int M6=numberStudent/6;
return M6;
}
~Student();
void look_list();
friend void mostrarDatos (Student &stus1, List &lis1);
};

int Student::numberStudent=0;

//CLASE "MODERATOR", TRES ATRIBUTOS, TRES METODOS ->(UN CONSTRUCTOR)


class Moderator : public Username{
private:
string role;
string controlSchedule;
int salary;
public:
Moderator(string, string, int, string, string, int);
void report();
void introduceOneself();
void look_at_the_list();

1
4
Práctica N° 8: Plantillas de Función y Clase en C++

};

//CLASE "BOOK" CON CONSTRUCTOR VACIO, Y METODOS GET Y SET (ARREGLOS


OBJETOS)
class Book{
private:
string author;
string title;
public:
Book(){
author="";
title="";
}
void getBook (string _author, string _title){
author= _author;
title= _title;
}

string setBook (){


return "you have added the course books: "+title+" with author " +author;
}
};

//CLASE "LIST" ( 2 CONSTRUCTORES Y UNA FUNCION AMIGA)


class List {
public:
List();
List(int _bookRead);
private:
int bookRead;
friend void mostrarDatos (Student &stus1, List &lis1);
};

class Mobiledevice {

1
5
Práctica N° 8: Plantillas de Función y Clase en C++

private:
string trademark;
string cost;
private:
string model;
string getModel(){
return model;
}
public:
Mobiledevice(string _trademark, string _cost, string _model){
this->trademark=_trademark;
this->cost=_cost;
this->model=_model;
}
};

class Laptop: protected Mobiledevice{


private:
int RAM;
public:
Laptop(string _trademark, string _cost, string _model,int
_RAM):Mobiledevice(_trademark,_cost,_model){
this->RAM=_RAM;
}
string gettestRAM(){
if (RAM==2)
return "YOUR DEVICE NEEDS TO IMPROVE";
else if (RAM==4)
return "YOUR DEVICE IS GOOD";
else if (RAM==8)
return "YOUR DEVICE IS EXCELLENT";
else if (RAM==16)
return "YOUR DEVICE IS OPTIMAL";
else if (RAM==32)
return "YOUR DEVICE IS VERY OPTIMAL";
else
1
6
Práctica N° 8: Plantillas de Función y Clase en C++

return "RAM MEMORY IS INCORRECT";


}
};

class Acess {
public:
int a,b,c,d,e;
public:
friend class Adiccionalscore;
};

class Adicionalscore{
protected:
Acess score;
public:
void showmyscore();
};

void Adicionalscore::showmyscore(){
cout<<"How many times did week 1 access the virtual library?"<<endl;
cin>>score.a;
cout<<"How many times did week 2 access the virtual library?"<<endl;
cin>>score.b;
cout<<"How many times did week 3 access the virtual library?"<<endl;
cin>>score.c;
cout<<"How many times did week 4 access the virtual library?"<<endl;
cin>>score.d;
score.e=(score.a+score.b+score.c+score.d)/4;
cout<<"Su puntaje adicional es: "<<score.e<<endl;

}
Username::~Username(){
cout<<""<<endl;
}
1
7
Práctica N° 8: Plantillas de Función y Clase en C++

Student::~Student(){
cout<<"";
}
//CONSTRUCTOR VACIO DE LA CLASE BASE USUARIO
Username::Username(){
}
//CONSTRUCTOR DE LA CLASE BASE USUARIO
Username::Username(string _name,string _gender,int _age){
name=_name;
gender= _gender;
age= _age;
}

void Username::look_list(){
cout<<"Name: "<<name<<endl;
cout<<"Gender: "<<gender<<endl;
cout<<"Age: "<<age<<endl;
}

//CONSTRUCTOR DE LA CLASE ESTUDIANTE SIN PARAMETROS[ojo cada vez que se instancie


un objeto, la variable "number student" aumenta
Student::Student(){
student_code="";
grade="";
section="";
numberStudent++;
}

//CONSTRUCTOR DE LA CLASE ESTUDIANTE CON SOLO UN PARAMETRO


Student::Student(string _student_code){
student_code=_student_code;
}

//CONSTRUCTOR DE LA CLASE DERIVADA ESTUDIANTE


Student::Student(string _student_code, string _grade, string _section){
1
8
Práctica N° 8: Plantillas de Función y Clase en C++

student_code= _student_code;
grade = _grade;
section = _section;
}

//CONSTRUCTOR CON HERENCIA COMPLETA


Student::Student(string _name,string _gender,int _age, string _student_code, string _grade, string
_section) : Username(_name,_gender,_age){
student_code= _student_code;
grade = _grade;
section = _section;
}

void Student::look_list(){
Username::look_list();
cout<<"Student code: "<<student_code<<endl;
cout<<"Grade: "<<grade<<endl;
cout<<"Section: "<<section<<endl;
}

//CONSTRUCTOR CON HERENCIA COMPLETA


Moderator::Moderator(string _name, string _gender, int _age, string _role, string _controlSchedule,
int _salary) : Username(_name,_gender,_age){
role = _role;
controlSchedule = _controlSchedule;
salary = _salary;
}

//metodo virtual
void Moderator::look_at_the_list(){
Username::look_list();
cout<<" Role: "<<role<<endl;
cout<<" Schudele control: "<<controlSchedule<<endl;
cout<<" Salary: "<<salary;
}

1
9
Práctica N° 8: Plantillas de Función y Clase en C++

void Username::setregister(string _name, string _gender, int _age){


name= _name;
gender= _gender;
age= _age;
}

void Username::show_data(){
cout<<"\t\tHello "<<name<<endl;
cout<<"\t\tyour gender is "<<gender<<endl;
if (gender=="Male"|| gender=="male")
cout<<"\t\tyour are "<<age<<" years old"<<endl;
else
cout<<"\t\tyour are "<<age<<" years old"<<endl;
}

void Student:: study (){


show_data();
cout<<"\t\tStudent your code is"<<student_code<<endl;
if (section=="A"){
cout<<"\t\tyour studying: "<<endl;
cout<<"\t\t -English "<<endl;
cout<<"\t\t -Math"<<endl;
cout<<"\t\t -Communication"<<endl;
}
else {
cout<<"\t\tyour studying: "<<endl;
cout<<"\t\t -Biology "<<endl;
cout<<"\t\t -Civic"<<endl;
cout<<"\t\t -Physical"<<endl;
}

2
0
Práctica N° 8: Plantillas de Función y Clase en C++

void Moderator:: report (){


show_data();
cout<<"-------------------------------------"<<endl;
cout<<"You have made a report successfully"<<endl;
cout<<"----------------------------------------"<<endl;
}

List::List(){
bookRead=0;
}

List::List(int _bookRead){
bookRead=_bookRead;
}

void mostrarDatos (Student &stus1, List &lis1){


cout<<"Code of student: "<<stus1.student_code<<endl;
cout<<"Numbre of books read"<<lis1.bookRead<<endl;;
}

//Todo lo que compila

int main(){
string _name, _gender, _student_code, _grade,_role,_controlSchedule, _section, typeuser,
decision;
int _age, _salary;
Username use1;
cout<<""<<endl;
cout<<""<<endl;
cout<<""<<endl;
cout<<""<<endl;
cout<<""<<endl;
cout<<""<<endl;
cout<<""<<endl;
2
1
Práctica N° 8: Plantillas de Función y Clase en C++

cout<<"\t\tWelcome username to the library virtual!!!"<<endl;


cout<<" "<<endl;
cout<<"\t\t\tWant to enter? [yes or not]"<<endl;
cout<<" "<<endl;
cout<<"\t\t\t|-> ";
cin>>decision;
if (decision=="yes"){
cout<<""<<endl;
cout<<"----------------------------------------"<<endl;
cout<<"Enter your first name: "<<endl;
cin>>_name;
cout<<"Enter your gender: "<<endl;
cin>>_gender;
cout<<"Enter your age: "<<endl;
cin>>_age;
//constructor de clase base
use1.setregister(_name,_gender,_age);
system ("cls");
cout<<""<<endl;
cout<<""<<endl;
cout<<""<<endl;
cout<<""<<endl;
cout<<""<<endl;
cout<<""<<endl;
cout<<""<<endl;
cout<<""<<endl;
cout<<""<<endl;
cout<<"\t\t\tAre you student or moderator?: ";
cin>> typeuser;
if (typeuser=="student"){
string decision2;
do{
system ("cls");
cout<<""<<endl;
cout<<""<<endl;

2
2
Práctica N° 8: Plantillas de Función y Clase en C++

cout<<""<<endl;
cout<<"\t\t------------------------------------"<<endl;
cout<<"\t\tEnter your student code: ";
cin>>_student_code;
cout<<""<<endl;
cout<<"\t\tEnter your grade: ";
cin>>_grade;
cout<<""<<endl;
cout<<"\t\tEnter your section: ";
cin>>_section;
//usando un constructor de herencia
Student stu1 (_name,_gender,_age,_student_code,_grade,_section);
cout<<"\t\t-----------------------------------------------------"<<endl;
stu1.study();
cout<<"\t\t-----------------------------------------------------"<<endl;
cout<<"\t\tIs a correct? yes or not "<<endl;
cin>>decision2;
}while(decision2=="not");
system("cls");
int opc;
cout<<"-------------------| MENU |-------------------"<<endl;
cout << "\n\t\t\t[1] See all courses " << endl;
cout << "\n\t\t\t[2] Add book " << endl;
cout << "\n\t\t\t[3] Evaluate mobile device " << endl;
cout << "\n\t\t\t[4] Exit " << endl;
cout<<"---------------------------------------------------------"<<endl;
do {
cout << "\n\t\t Enter an option: ";
cin >> opc;
} while (opc != 1 && opc != 2 && opc != 3 && opc != 4);
switch (opc) {
case 1:
{system("cls");
cout<<"\t------------------------|Courses|----------------"<<endl;
cout<<"\t -MATHEMATICS"<<endl;

2
3
Práctica N° 8: Plantillas de Función y Clase en C++

cout<<"\t -ENGLISH"<<endl;
cout<<"\t -BIOLOGY"<<endl;
cout<<"\t -SOCIAL PERSON"<<endl;
cout<<"\t -PHYSICAL EDUCATION"<<endl;
cout<<"\t -CIVICS"<<endl;
cout<<"\t -PHYSICAL"<<endl;
}
break;
case 2:
{system("cls");
//Usando arreglo de objetos
cout<<""<<endl;
cout<<""<<endl;
cout<<"\tAdd book........."<<endl;
int n;
cout<<""<<endl;
cout<<"\thow many books do you want to add?: ";
cin>>n;
Book books[n];
int contador=0;
cout<<"\t-----------------------------------"<<endl;
do{
string a;
string t;
cout<<""<<endl;
cout<<"\tEnter book course: ";
cin>>t;
cout<<"\tEnter the first name of the author of the book: ";
cin>>a;
cout<<""<<endl;
books[contador].getBook(a,t);
contador++;
}while(contador<n);
cout<<"-----------------------------------"<<endl;
cout<<"THE BOOKS ARE: "<<endl;

2
4
Práctica N° 8: Plantillas de Función y Clase en C++

for (int i=0; i<n; i++){


cout<<books[i].setBook()<<endl;
}
string opc5;
cout<<"You want to know your score in this month?: ";
cin>>opc5;
if (opc5=="yes"){
Adicionalscore as1;
as1.showmyscore();
}
else{
cout<<"";
}
}
break;
case 3:
{system("cls");
string _trademark,_cost,_model;
int _RAM;
cout<<"Registering........."<<endl;
cout<<""<<endl;
cout<<"Enter the brand of your mobile device: ";
cin>>_trademark;
cout<<"Enter the cost of your device: ";
cin>>_cost;
cout<<"Enter your product model: ";
cin>>_model;
cout<<"Enter the amount of RAM: ";
cin>>_RAM;
Laptop* L1= new Laptop(_trademark,_cost,_model,_RAM);
cout<<"------RESULT-------"<<endl;
cout<<L1->gettestRAM()<<endl;
}
break;
case 4:

2
5
Práctica N° 8: Plantillas de Función y Clase en C++

{
system("pause");
return 0;
}
break;
}
}
else {

cout<<"Enter the role you play on the platform: ";


cin>>_role;
cout<<"Enter your control schedule: ";
cin>>_controlSchedule;
cout<<"Enter your salary amount: ";
cin>>_salary;
//usando un constructor de herencia
Moderator mod1(_name,_gender,_age,_role,_controlSchedule,_salary);
cout<<"----------------------------------"<<endl;
system("cls");
int opc;
cout<<"----------------------|MENU|----------------------"<<endl;
cout << "\n\t[1] Register reported student " << endl;
cout << "\n\t[2] Report" << endl;
cout << "\n\t[3] Watch conected student" << endl;
cout << "\n\t[4] Divide student" << endl;
cout << "\n\t[5] Register new student or specialist"<<endl;
cout << "\n\t[6] Exit" << endl;
do {
cout << "\n\t Enter an option: ";
cin >> opc;
} while (opc != 1 && opc != 2 && opc != 3 && opc != 4 && opc != 5 && opc !=6);
switch (opc) {
case 1:
{system("cls");
//usando funciones amigas
2
6
Práctica N° 8: Plantillas de Función y Clase en C++

string n,s,e;
int c;
cout<<"Going to register a student........"<<endl;
cout<<"What is the code of the student?"<<endl;
cin>>n;
cout<<"What is the grade?"<<endl;
cin>>s;
cout<<"What is the seccion?"<<endl;
cin>>e;
cout<<"How many books has the student read?"<<endl;
cin>>c;
Student stus1(n);
List lis1(c);
cout<<"_____________________________________"<<endl;
cout<<"You have recorded that: "<<endl;
mostrarDatos(stus1,lis1);
system("pause");
}
break;
case 2:
{system("cls");
cout<<"Next you will inform.........."<<endl;
mod1.report();
cout<<"--------------------------------"<<endl;
}
break;
case 3:
{
//usando atributos estaticos
system("cls");
cout<<"Number of the student in platform is: ";
Student p1;
Student p2;
Student p3;
cout<<p1.getnumberStudent()<<endl;

2
7
Práctica N° 8: Plantillas de Función y Clase en C++

}
break;

case 4:
{
//usando metodos estaticos estaticos
system("cls");
string opc3;
cout<<""<<endl;
cout<<""<<endl;
cout<<"\t\tNumber of the student in platform is: ";
Student p1;
Student p2;
Student p3;
Student p4;
Student p5;
Student p6;
Student p7;
Student p8;
Student p9;
Student p10;
Student p11;
Student p12;
cout<<p1.getnumberStudent()<<endl;
cout<<""<<endl;
cout<<"\t\tYou want to separarte for rooms?: ";
cin>>opc3;
if(opc3 =="yes"){
int numberrooms;
cout<<""<<endl;
cout<<"How many rooms do you want to do?? [2/4/6]: ";
cin>>numberrooms;
if(numberrooms==2){
cout<<""<<endl;
cout<<"The number of each member in the room are:
2
8
Práctica N° 8: Plantillas de Función y Clase en C++

"<<Student::dividir2()<<endl;
}
else if(numberrooms==4){
cout<<""<<endl;
cout<<"The number of each member in the room are:
"<<Student::dividir4()<<endl;
}
else {
cout<<""<<endl;
cout<<"The number of each member in the room are:
"<<Student::dividir6()<<endl;
}
}
else
{cout<<""<<endl;
cout<<"Not room has been created today"<<endl;
}
}
break;

case 5: {
//utilizamos metodos virtuales
int j;
int n;
cout<<"Enter who you want to register: [1] Students - [2] Specialist"<<endl;
cin>>n;
cout<<"How many do you want to register?"<<endl;
cin>>j;
Username *vector[j];
for (int i=0; i<j; i++){
//atributos de la clase base
string _name;
string _gender;
int _age;
//atributos de la clase estudiante
string _student_code;
2
9
Práctica N° 8: Plantillas de Función y Clase en C++

string _grade;
string _section;
//atributos de la clase moderador
string _role;
string _controlSchedule;
int salary;
if (n==1){
cout<<"Enter the name of the new student"<<endl;
cin>>_name;
cout<<"Enter the gender of the new student"<<endl;
cin>>_gender;
cout<<"Enter the age of the new student"<<endl;
cin>>_age;
cout<<"Enter the new student's code"<<endl;
cin>>_student_code;
cout<<"Enter the grade of the new student"<<endl;
cin>>_grade;
cout<<"Enter the section of the new student"<<endl;
cin>>_section;
vector [i] =new Student(_name,_gender,_age,_student_code,_grade,_section);
}
else {
cout<<"Enter the name of the new specialist"<<endl;
cin>>_name;
cout<<"Enter the gender of the new specialist"<<endl;
cin>>_gender;
cout<<"Enter the age of the new specialist"<<endl;
cin>>_age;
cout<<"Enter the age of the new specialist"<<endl;
cin>>_age;
cout<<"Enter the role of the new specialist"<<endl;
cin>>_role;
cout<<"enter your new specialist control schedule"<<endl;
cin>>_controlSchedule;
cout<<"enter the salary of the new specialist"<<endl;

3
0
Práctica N° 8: Plantillas de Función y Clase en C++

cin>>_salary;
vector [i] = new Moderator(_name,_gender,_age, _role,_controlSchedule,_salary);
}

}
cout<<"|-------------You have registered--------------------|"<<endl;
for (int i=0; i<j; i++){
vector[i]->look_list();
cout<< "\n";
}
}
break;

case 6:
{
system("pause");
}
break;
}

}
system ("pause");
return 0;

}
else{
system("cls");
cout<<""<<endl;
cout<<""<<endl;
cout<<""<<endl;
cout<<""<<endl;
cout<<""<<endl;
cout<<""<<endl;
3
1
Práctica N° 8: Plantillas de Función y Clase en C++

cout<<""<<endl;
cout<<"\t\t\t----------------------------------"<<endl;
cout<<"\t\t\t| You left the virtual library |"<<endl;
cout<<"\t\t\t---------------------------------"<<endl;
cout<<""<<endl;
cout<<""<<endl;
cout<<""<<endl;
cout<<""<<endl;
cout<<""<<endl;
cout<<""<<endl;
//destructor de clase base
use1.~Username();
cout<<""<<endl;
cout<<""<<endl;
system ("pause");
return 0;
}
}

----------------------------------| Interno |-------------------------------------

//Ver la disponibilidad de los libros

#include <iostream>
#include <conio.h>
using namespace std;

class Book {
public:
string title;
string author;
int n=8;
int m=30;
int o=60;

3
2
Práctica N° 8: Plantillas de Función y Clase en C++

void showData();
virtual void inform_quantity() = 0;
virtual void plusNewBook(int) = 0;
};

void Book::showData() {
cout << "Title: " << title << endl;
cout << "Author: " << author<< endl;
}

class philosophy_psychology: public Book {


public:
void plusNewBook(int x){n=n+x;}
void inform_quantity() { cout << "I have "<<n<<" books available in aisle 18-C"<<endl; }
};
class Religionculture: public Book {
public :
void plusNewBook(int y){m=m+y;}
void inform_quantity() { cout << "I have "<<m<<" books available in aisle 19-A"<<endl; }
};
class ScienceBasic : public Book {
public:
void plusNewBook(int z){o=o+z;}
void inform_quantity(){ cout<<"I have "<<o<<" books available in aisle 12-B"<<endl;}
};
////////////////////////////////////////////////////////
//Plantilla de funciones
template <typename L>
void Toexchange(L BookI, L BookII){
L BookIII=BookI;
BookI=BookII;
BookII=BookIII;
cout<< "Now your book is "<<BookI<<" and the book of the other user is "<<BookII<<endl;
}
/////////////////////////////////////////////////////////

3
3
Práctica N° 8: Plantillas de Función y Clase en C++

//plantilla de clases
template <class NP>
class numero{
NP alumI,alumII;
public:
numero(NP _alumI, NP _alumII){
alumI = _alumI;
alumII = _alumII;
}

NP May();
};

template <class NP>


NP numero <NP>::May(){return(alumI>alumII? alumI : alumII);}
////////////////////////////////////////////////////////////////
//Plantillas metodos
template <class var>
var comparable (var x, var y){
if (x=="International" && y=="Europe"){
return "aisle nine";
}
else if (x=="International" && y=="Asia") {
return "aisle ten";

}
else if (x=="International" && y=="North America"){
return "aisle five";
}
else if (x=="International" && y=="Africa"){
return "aisle four";
}
else if (x=="International" && y=="Oceania"){
return "aisle five";
}
3
4
Práctica N° 8: Plantillas de Función y Clase en C++

if (x=="National" && y=="Europe"){


return "aisle A";
}
else if (x=="National" && y=="Asia") {
return "aisle B";

}
else if (x=="National" && y=="North America"){
return "aisle C";
}
else if (x=="National" && y=="Africa"){
return "aisle D";
}
else if (x=="National" && y=="Oceania"){
return "aisle E";
}
else{
return "Error Description";
}

int main()
{
cout<<"---------------------|R E P O S I T O R Y|-----------------" <<endl;
philosophy_psychology T1;
T1.title = "Child's behavior";
T1.author = "Chris Paul";
T1.showData();
T1.inform_quantity();
cout<<"------------------------------------------------------------"<<endl;
Religionculture P1;
P1.title = "Love is God";
P1.author = "San Lucas tadeo";
3
5
Práctica N° 8: Plantillas de Función y Clase en C++

P1.showData();
P1.inform_quantity();
cout<<"------------------------------------------------------------"<<endl;
ScienceBasic B2;
B2.title = "Brain and muscles";
B2.author = "Albert Frollo";
B2.showData();
B2.inform_quantity();

cout<<"\n------------------------------------------------------------"<<endl;
cout<<" want to add more books available?"<<endl;
cout<<"------------------------------------------------------------"<<endl;
string Newopc;
cin>>Newopc;
if (Newopc=="yes"||Newopc=="YES"||Newopc=="Yes"){
system("cls");
cout<<"how many books do you want to add [T1]?"<<endl;
int x;
cin>>x;
T1.plusNewBook(x);
cout<<"how many books do you want to add [P1]?"<<endl;
int y;
cin>>y;
P1.plusNewBook(y);
cout<<"how many books do you want to add [B2]?"<<endl;
int z;
cin>>z;
B2.plusNewBook(z);
cout<<"--------------------| U P D A T E D D A T A |---------------------"<<endl;
T1.showData();
T1.inform_quantity();
cout<<"-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o"<<endl;
P1.showData();
P1.inform_quantity();
cout<<"-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o"<<endl;

3
6
Práctica N° 8: Plantillas de Función y Clase en C++

B2.showData();
B2.inform_quantity();
cout<<"-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o"<<endl;
cout<<"\n\n------------------------------------------------------------"<<endl;
cout<<" You want to refund a library book?"<<endl;
cout<<"------------------------------------------------------------"<<endl;
string Newopc2;
cin>>Newopc2;
if (Newopc2=="yes"||Newopc=="YES"||Newopc=="Yes"){
//Intercambio de venta
system("cls");
string BookI;
string BookII;
cout<<"Enter the book title you want to refund"<<endl;
cin>>BookI;
cout<<"Enter the title of the book you want delivered"<<endl;
cin>>BookII;
cout<<"\n\n-------------------------------------------------------"<<endl;
Toexchange(BookI,BookII);
cout<<"\n\n------------------------------------------------------------"<<endl;
cout<<" You want to compare the condition of the book? "<<endl;
cout<<"------------------------------------------------------------"<<endl;
string Newopc2;
cin>>Newopc2;
if (Newopc2=="yes"||Newopc=="YES"||Newopc=="Yes"){
//Evaluar algun libro
system("cls");
cout<<"Enter name of the title of the first book"<<endl;
int a1,a2,b1,b2,c1,c2,d1,d2;
float proml1,proml2;
string t1;
cin>>t1;
cout<<"1.Information: [1] Terrible, [2] Bad, [3] Fair, [4] Good, [5] Excellent"<<endl;
cin>>a1;
cout<<"2.Interest to the reader: [1] Terrible, [2] Bad, [3] Fair, [4] Good, [5] Excellent"<<endl;

3
7
Práctica N° 8: Plantillas de Función y Clase en C++

cin>>b1;
cout<<"3.Endurance: [1] Terrible, [2] Bad, [3] Fair, [4] Good, [5] Excellent"<<endl;
cin>>c1;
cout<<"4.Availability: [1] Terrible, [2] Bad, [3] Fair, [4] Good, [5] Excellent"<<endl;
cin>>d1;
proml1=(a1+b1+c1+d1)/4;
cout<<"Now Enter name of the title of the second book"<<endl;
string t2;
cin>>t2;
cout<<"1.Information: [1] Terrible, [2] Bad, [3] Fair, [4] Good, [5] Excellent"<<endl;
cin>>a2;
cout<<"2.Interest to the reader: [1] Terrible, [2] Bad, [3] Fair, [4] Good, [5] Excellent"<<endl;
cin>>b2;
cout<<"3.Endurance: [1] Terrible, [2] Bad, [3] Fair, [4] Good, [5] Excellent"<<endl;
cin>>c2;
cout<<"4.Availability: [1] Terrible, [2] Bad, [3] Fair, [4] Good, [5] Excellent"<<endl;
cin>>d1;
proml2=(a2+b2+c2+d2)/4;
numero<int>dosnum(proml1,proml2);
if (proml1==dosnum.May()){
cout<<"Book is recommended: "<<t1<<endl;
}
else{
cout<<"Book is recommended: "<<t2<<endl;
}
cout<<"\n\n------------------------------------------------------------"<<endl;
cout<<" need to locate a book? "<<endl;
cout<<"------------------------------------------------------------"<<endl;
string Newopc2;
cin>>Newopc2;
if (Newopc2=="yes"||Newopc=="YES"||Newopc=="Yes"){
system("cls");
string _x,_y;
cout<<"is it a national or international book?"<<endl;
cin>>_x;

3
8
Práctica N° 8: Plantillas de Función y Clase en C++

cout<<"What continent is the book from?"<<endl;


cin>>_y;
cout<<"--------------------------------------"<<endl;
cout<<"Congratulations The book is in "<<comparable(_x,_y);
}
else{
cout<<"Thank for get your answer"<<endl;
}
}
else{
cout<<"Thank for get your answer"<<endl;
}
}
else{
cout<<"Thank for get your answer"<<endl;
}
}
else{
cout<<"Thank for get your answer"<<endl;
}

return 0;

3
9
Práctica N° 8: Plantillas de Función y Clase en C++

6. CONCLUSIONES DE LA PRÁCTICA:
En la sobrecarga de funciones, se declara y define más de una función con el mismo nombre. Esto
hace que el programa sea más complejo y extenso. Para superar este problema, se utiliza la plantilla
de funciones. En una plantilla de función, se define una función sin tipo único de modo que se puedan
pasar argumentos de cualquier tipo de datos estándar a la función. Es así que en equipo, podemos
concluir que una plantilla, ya sea de función o una en base a POO, permite trabajar no solo
limitándonos a un solo tipo de variable.

7. CUESTIONARIO

1. ¿Qué es la programación de genérica?


La programación genérica es la cual esta mucho mas centrado en los algoritmos que en los
datos.

2. ¿Qué es un template?
También son llamadas plantillas son aquellas en la cual se usa de forma especial de escribir
las clases y funciones para que estas sean usadas con cualquier tipo de dato.

3. ¿Cuántos tipos de templates existen?


Hay 2 tipos de templates: Funciones templates y clases templates.

4. ¿Qué es la programación genérica?


Es aquella la cual está centrada más en los algoritmos y principalmente puede sintetizarse en
la palabra generalización.

5. ¿Qué es una plantilla de función?


Debe utilizarse en lugar de los nombres de los tipos de datos por lo que esta da una forma
especial de escribir las funciones y las clases.

6. ¿Qué es una plantilla de método?


La plantilla es un patrón de diseño de comportamiento que define el esqueleto de un
algoritmo en la superclase pero permite que las subclases sobrescriban pasos del algoritmo
sin cambiar su estructura.

7. ¿Qué es una plantilla de clase?


Una característica poderosa de C ++ es que puede crear clases de plantilla que son clases que
pueden tener miembros del tipo genérico, es decir, miembros que usan parámetros de
plantilla como tipos.

8. ¿Cómo se usa una plantilla de función?


Para usar las plantillas de funciones se tiene que utilizarlas como funciones normales.

9. ¿Cómo se declara una plantilla de clase?


4
0
Práctica N° 8: Plantillas de Función y Clase en C++

Para crear una instancia de una clase de plantilla de forma explícita, siga la palabra clave de
plantilla con una declaración para la clase, con el identificador de clase seguido de los
argumentos de la plantilla.

10. ¿Qué podemos usar como miembros de una plantilla de clase?


Es recomendable utilizar como miembros a plantillas orientadas a funciones, siempre y
cuando colocando sus respectivos parámetros. Entre las plantillas de funciones mas conocidas
están los constructores las anidadas.
11. ¿Cómo se declaran objetos de una plantilla de clase?
Antes de poder declarar los objetos, es importante sobrecargar el operador de comparación
“>”, de esta manera podemos llamar sin ningun problema a la clase por el siguiente esquema
( “nombre_clase <tipo_dato> nombre_objeto(argumentos_constructor)”).

12. ¿Cómo se usa una plantilla de clase?


A menudo es utilizado junto a los operadores sobrecargados, permitiendo utilizar las
matrices y los arreglos con una mayor flexibilidad, cuando llamemos un objeto.

13. ¿Qué ventajas tiene las plantillas frente al polimorfismo?


A diferencia del polimorfismo, este tiene la ventaja de utilizar en sus parámetros cualquier
tipo de variables con lo cual es posible solucionar diferentes problemas, en base a este es más
fácil realizar un mantenimiento al código.

14. ¿Cómo se construye una clase recipiente?


Se construyen dentro de las clases, permitiendo la construcción de listas simplemente
enlazadas y de esta manera será más fácil reconocer atributos y métodos con mayor
facibilidad

8. BIBLIOGRAFÍA

1. J. Valiño J. Zarazaga S. Comella J. Nogueras P. R. Muro-Medrano.,” Utilización de técnicas


de programación basadas en frames para incrementar la potencia de representación en clases
de C++ para aplicaciones de sistemas de información” [En línea]. Disponible:
https://bit.ly/3trqxJa [Accedido:02 julio 2021]
2. Deitel, H., Deitel, P. (2002). C++, How to Program, 5th edition, [En línea] Disponible:
https://bit.ly/3d7lSWO [Accedido:02 julio 2021]
3. Deitel.,Harvey M. y Paul,J.,”Como Programar en C/C++ y Java”, cuarta edición., [En línea].
Disponible: https://bit.ly/3gdOAYh [Accedido:02 julio 2021]
4. Fco.Javier Ceballos Sierra:” Programación orientada a objetos c++ cuarta edición” [En línea].
Disponible: https://bit.ly/3al02NQ [Accedido:03 julio 2021]

4
1

También podría gustarte