Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

27
Informática II Clase 10: Clases y funciones especiales 1 Diego Fernando Serna Restrepo Semestre 2011/2

Transcript of Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

Page 1: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

Informática II

Clase 10: Clases y funciones especiales

1Diego Fernando Serna Restrepo Semestre 2011/2

Page 2: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

Informática II 2011/22

CHISTE DEL DÍA

Page 3: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

3

CONTENIDO

Informática II 2011/2

Variables miembro estáticas1

Funciones miembro estáticas2

Punteros a funciones3

4 Arreglo de punteros a funciones

Page 4: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

4

CLASES Y FUNCIONES ESPECIALES

Informática II 2011/2

• Hasta ahora se ha estudiado diferentes mecanismos que tiene C++ para manipular variables: variables globales, variables locales de las funciones, punteros a variables y variables miembro.

• En C++ existen métodos para que diferentes objetos del mismo tipo puedan compartir variables y funciones.

Page 5: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

Informática II 2011/25

DATOS MIEMBRO ESTÁTICOS

1

•Las variables miembro declaradas como static son compartidas a lo largo de las instancias de la clase.

2

•Se dice que una variable miembro static pertenece como tal a la clase en vez de al objeto, es por ello que se puede tener acceso a ella como si se tratase de una variable global

3

•A pesar de que la variable es estática y privada, cualquier método de la clase puede tener acceso a ella o a cualquier otra variable miembro.

Page 6: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

Informática II 2011/26

DATOS MIEMBRO ESTÁTICOS

4

•Incluso no se hace necesario instanciar un objeto de la clase para tener acceso directo a esta, si es definida como publica.

5

•Las variables miembro normales son creadas por cada objeto instanciado, pero solo existe una variable estática por clase.

Buena practica de programaciónEs preferible definir la variable estática como privada y otorgarle un método de acceso público, sin embargo de esta manera se debe crear primero un objeto para a través de él poder acceder al método.

Page 7: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

7Informática II 2011/2

DATOS MIEMBRO ESTÁTICOS#include <iostream>using namespace std;class Cat { public: Cat(int age):itsAge(age){HowManyCats++; } virtual ~Cat() { HowManyCats--; } virtual int GetAge() { return itsAge; } virtual void SetAge(int age) { itsAge = age; }

static int HowManyCats; private: int itsAge; };

int Cat::HowManyCats = 0; int main() { const int MaxCats = 5; int i; Cat *CatHouse[MaxCats]; for (i = 0; i<MaxCats; i++) CatHouse[i] = new Cat(i); for (i = 0; i<MaxCats; i++) { cout << "There are "; cout << Cat::HowManyCats; cout << " cats left!\n"; cout << "Deleting the one which is "; cout << CatHouse[i]->GetAge(); cout << " years old\n"; delete CatHouse[i]; CatHouse[i] = 0; } return 0; }

"There are “ 5 cats left Deleting the one which is 0 years old"There are “ 4 cats left Deleting the one which is 1 years old"There are “ 3 cats left Deleting the one which is 2 years old"There are “ 2 cats left Deleting the one which is 3 years old"There are “ 1 cats left Deleting the one which is 4 years old

Page 8: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

Informática II 2011/28

TIPS AL USAR DATOS MIEMBROS ESTÁTICOS

*

•Use variables miembro estáticas para compartir datos entre todas las instancias de una clase.

*

•Declare variables miembro estáticas protected o private, si desea restringir el acceso a estas.

*

•No utilice variables miembro estáticas para almacenar datos de un objeto.

Page 9: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

9

CONTENIDO

Informática II 2011/2

Variables miembro estáticas1

Funciones miembro estáticas2

Punteros a funciones3

4 Arreglo de punteros a funciones

Page 10: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

Informática II 2011/210

FUNCIONES MIEMBRO ESTÁTICAS

También se puede acceder a estos métodos estáticos a través de un objeto creado, similar a

como es llamado un método miembro cualquiera.

Las funciones miembro estáticas son como las variables miembro estáticas, existen no para cada

objeto, sino por clase, por ello pueden ser llamadas sin que se haya instanciado un objeto de la clase.

Page 11: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

Informática II 2011/211

FUNCIONES MIEMBRO ESTÁTICAS

class Cat{public: //…Constructor, destructor , otros metodos

static int GetHowMany() { return HowManyCats; }

static int HowManyCats;};

int Cat::HowManyCats = 0;

int main(){int howMany;Cat theCat; // define a cathowMany = theCat.GetHowMany(); // access through an objecthowMany = Cat::GetHowMany(); // access without an object}

Page 12: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

Informática II 2011/212

• Cuidado, las funciones miembro estáticas NO poseen un puntero this, ni tampoco pueden ser declaradas const.

• Como las funciones miembro utilizan el puntero this para acceder a las variables miembro, una función estática solo podrá acceder a los datos miembro que sean declarados estáticos.

FUNCIONES MIEMBRO ESTÁTICAS

Page 13: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

13

CONTENIDO

Informática II 2011/2

Variables miembro estáticas1

Funciones miembro estáticas2

Punteros a funciones3

4 Arreglo de punteros a funciones

Page 14: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

Informática II 2011/214

PUNTEROS A FUNCIONES

• Así como el nombre de un arreglo es un puntero constante al primer elemento del arreglo, el nombre de una función es un puntero constante a la función.

• Es posible declarar entonces una variable puntero que apunte a un función e invocar o llamar a la función original a través de él.

Esto puede ser muy útil, al permitir crear programas que decidan qué función llamar basándose en la elección del usuario en tiempo de ejecución.

Page 15: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

Informática II 2011/215

• Un puntero a función debe apuntar siempre a una función con el mismo tipo de retorno y firma.

PUNTEROS A FUNCIONES

long (* funcPtr) (int);

funcPtr: es declarado para ser un puntero que apunta a una función que toma un entero int como parámetro de entrada y retorna un long.

El paréntesis al rededor de * funcPtr es necesario

Page 16: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

Informática II 2011/216

Para asignar un puntero a una función, simplemente se iguala este al nombre de la función.

PUNTEROS A FUNCIONES

void (* pFunc) (int &, int &); //puntero a funcionvoid GetVals(int&, int&); //funcionpFunc = GetVals; //puntero a funcion getVals

Para hacer el llamado a la función a través del puntero, simplemente use el puntero a función de la misma forma como usaría el nombre de la función

pFunc(valOne, valTwo); //llamdo de la funcion

Page 17: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

Informática II 2011/217

#include <iostream> using namespace std; void Square (int&,int&); void Cube (int&, int&); void Swap (int&, int &); void GetVals(int&, int&); void PrintVals(int, int);

PUNTEROS A FUNCIONESint main() { void (* pFunc) (int &, int &); bool fQuit = false; int valOne=1, valTwo=2; int choice; while (fQuit == false) { cout << "(0)Quit (1)Change Values (2)Square

(3)Cube (4)Swap: "; cin >> choice; switch (choice) { case 1: pFunc = GetVals; break; case 2: pFunc = Square; break; case 3: pFunc = Cube; break; case 4: pFunc = Swap; break; default : fQuit = true; break; } if (fQuit) break; PrintVals(valOne, valTwo); pFunc(valOne, valTwo); PrintVals(valOne, valTwo); } return 0; }

void PrintVals(int x, int y) { cout << "x: " << x << " y: " << y << endl; }

void Square (int & rX, int & rY) { rX *= rX; rY *= rY; }

void Cube (int & rX, int & rY) { int tmp; tmp = rX; rX *= rX; rX = rX * tmp; tmp = rY; rY *= rY; rY = rY * tmp; }

void Swap(int & rX, int & rY) { int temp; temp = rX; rX = rY; rY = temp; }

void GetVals (int & rValOne, int & rValTwo){ cout << "New value for ValOne: "; cin >> rValOne; cout << "New value for ValTwo: "; cin >> rValTwo; }

Page 18: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

Informática II 2011/218

PUNTEROS A FUNCIONES

• Los punteros a funciones reducen código duplicado, clarifican el programa, y permite hacer tablas de funciones a llamar en tiempo de ejecución.

// Listing 14.6 Without function pointers #include <iostream>int main() { bool fQuit = false; int valOne=1, valTwo=2; int choice; while (fQuit == false) { cout << "(0)Quit (1)Change Values (2)Square(3)Cube (4)Swap: "; cin >> choice; switch (choice) { case 1: PrintVals(valOne, valTwo); GetVals(valOne, valTwo); PrintVals(valOne, valTwo); break; case 2: PrintVals(valOne, valTwo); Square(valOne,valTwo); PrintVals(valOne, valTwo); break;

case 3: PrintVals(valOne, valTwo); Cube(valOne, valTwo); PrintVals(valOne, valTwo); break; case 4: PrintVals(valOne, valTwo); Swap(valOne, valTwo); PrintVals(valOne, valTwo); break; default : fQuit = true; break; } if (fQuit) break; } return 0; }

Page 19: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

Informática II 2011/219

PASANDO COMO ARGUMENTO A UNA FUNCIÓN, PUNTEROS A FUNCIONES

• Los punteros a funciones pueden ser pasados como argumentos a otras funciones, las cuales a su vez pueden llamar a otra función usando el puntero.

#include <iostream>using namespace std;void Square (int&,int&);void Cube (int&, int&);void Swap (int&, int &);void GetVals(int&, int&);void PrintVals(void (*)(int&, int&),int&, int&);

int main() { int valOne=1, valTwo=2; int choice; bool fQuit = false; void (*pFunc)(int&, int&); while (fQuit == false) { cout << "(0)Quit (1)Change Values

(2)Square (3)Cube (4)Swap: "; cin >> choice; switch (choice) { case 1:pFunc = GetVals; break; case 2:pFunc = Square; break; case 3:pFunc = Cube; break; case 4:pFunc = Swap; break; default:fQuit = true; break; } if (fQuit == true) break; PrintVals ( pFunc, valOne, valTwo); } return 0; }

void PrintVals( void (*pFunc)(int&, int&),int& x, int& y) { cout << "x: " << x << " y: " << y << endl; pFunc(x,y); cout << "x: " << x << " y: " << y << endl; }

Page 20: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

Informática II 2011/220

• Se puede usar typedef para simplificar las definiciones de punteros a funciones

PASANDO COMO ARGUMENTO A UNA FUNCIÓN, PUNTEROS A FUNCIONES

typedef void (*VPF) (int&, int&) ;

VPF pFunc;VPF pFunc2;

void (*pFunc3)(int&, int&);void (*pFunc4)(int&, int&);

Page 21: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

Informática II 2011/221

PUNTEROS A MÉTODOS DE UNA CLASE

Estos punteros a métodos se utilizan de la misma forma que los punteros a funciones, solo que necesitan un objeto de la clase

correcta con el cual invocarlos.

Para hacerlo se utiliza la misma declaración vista anteriormente pero se incluye el nombre de la función y el operador scope (::)

antes del nombre del puntero.

Hasta este momento todos los punteros han sido referenciados a funciones en general no incluidas en clases. También es posible

crear punteros a funciones miembro de una clase.

Page 22: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

Informática II 2011/222

PUNTEROS A MÉTODOS DE UNA CLASE

#include <iostream>using namespace std;

class Mammal { public: Mammal():itsAge(1) { } virtual ~Mammal() { } virtual void Speak() const = 0; virtual void Move() const = 0; protected: int itsAge; };

class Dog : public Mammal{ public: void Speak()const { cout << "Woof!\n"; } void Move() const { cout << "Walking ...\n"; } };

class Cat : public Mammal { public: void Speak()const { cout << "Meow!\n"; } void Move() const { cout << "slinking...\n"; } };

class Horse : public Mammal { public: void Speak()const { cout << "Whinny!\n"; } void Move() const { cout << "Galloping...\n"; } };

int main() { void (Mammal::*pFunc)() const =0; Mammal* ptr =NULL; int Animal; int Method; bool fQuit = false; while (fQuit == false) { cout << "(0)Quit (1)dog (2)cat (3)horse: "; cin >> Animal; switch (Animal) { case 1: ptr = new Dog; break; case 2: ptr = new Cat; break; case 3: ptr = new Horse; break; default: fQuit = true; break; } if (fQuit) break; cout << "(1)Speak (2)Move: "; cin >> Method; switch (Method) { case 1: pFunc = Mammal::Speak(); break; default: pFunc = Mammal::Move(); break; } (ptr->*pFunc)(); delete ptr; } return 0; }

Page 23: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

Informática II 2011/223

USANDO ARREGLOS DE PUNTEROS A MÉTODOS DE UNA CLASE.

•Como los punteros a funciones, los punteros a funciones miembro pueden ser almacenados en arreglos. El arreglo puede ser inicializado con la dirección de varias funciones miembro, y estas pueden ser llamadas mediante el índice del arreglo.

1

•Puede verse confuso en un principio, pero luego de creardo el vector, puede hacer el programa mucho más fácil de comprender y leer.

2

Llame los punteros referenciados a las funciones miembro de un objeto específico de una clase, usando typedef para hacer la definición de los punteros y las declaraciones más fácil de leer.

Page 24: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

Informática II 2011/224

USANDO ARREGLOS DE PUNTEROS A MÉTODOS DE UNA CLASE.

//Listing 14.11 Array of pointers to member functions #include <iostream>

using namespace std; class Dog { public: void Speak()const { cout << "Woof!\n"; } void Move() const { cout << "Walking to heel...\n"; } void Eat() const { cout << "Gobbling food...\n"; } void Growl() const { cout << "Grrrrr\n"; } void Whimper() const { cout << "Whining noises...\n"; } void RollOver() const { cout << "Rolling over...\n"; } void PlayDead() const { cout << "Is this the end of Little dog?\n"; } };

typedef void (Dog::*PDF)()const ; int main() { const int MaxFuncs = 7;

PDF DogFunctions[MaxFuncs] = { Dog::Speak, Dog::Move, Dog::Eat, Dog::Growl,

Dog::Whimper, Dog::RollOver, Dog::PlayDead }; Dog* pDog =NULL; int Method; bool fQuit = false; while (!fQuit) { cout << "(0)Quit (1)Speak (2)Move (3)Eat (4)Growl"; cout << " (5)Whimper (6)Roll Over (7)Play Dead: "; cin >> Method; if (Method == 0) { fQuit = true; } else { pDog = new Dog; (pDog->*DogFunctions[Method-1])(); delete pDog; } } return 0; }

Page 25: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

25Informática II 2011/2

GRACIAS POR SU ATENCIÓN

Page 26: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

26

BIBLIOGRAFÍA

• Pagina de Referencia lenguaje C++: • http://www.cplusplus.com/reference/std/ex

ception/exception/• http://www.cplusplus.com/reference/std/std

except/• Sams Teach yourselft C++ in 21 days:

http://newdata.box.sk/bx/c/htm/ch20.htm#Heading1

Informática II 2011/2

Page 27: Informática II 1 Diego Fernando Serna RestrepoSemestre 2011/2.

Informática II 2009/2

27