Ingen beskrivning
Jose Ortiz 6d0a969f91 Initial commit 9 år sedan
doc Initial commit 9 år sedan
images Initial commit 9 år sedan
Birds.pro Initial commit 9 år sedan
Birds.pro.user Initial commit 9 år sedan
README.md Initial commit 9 år sedan
bird.cpp Initial commit 9 år sedan
bird.h Initial commit 9 år sedan
filter.cpp Initial commit 9 år sedan
main.cpp Initial commit 9 år sedan
mainwindow.cpp Initial commit 9 år sedan
mainwindow.h Initial commit 9 år sedan
mainwindow.ui Initial commit 9 år sedan

README.md

English | Español

Utilizando objetos en C++ - Pájaros

main1.png main2.png main3.png

LAS IMAGENES DE ARRIBA NO SON LAS DE ESTE LAB SON LAS DEL LAB DE CONDICIONALES (USANDO OTRA VERSION DE BIRDS, BIRTH OF A BIRD). LAS IMAGENES ERAN LAS DE ABAJO

Hasta ahora hemos visto cómo utilizar variables para guardar y manipular datos de cierto tipo y cómo estructurar nuestros programas dividiendo las tareas en funciones. Un objeto es una entidad que se utiliza en muchos lenguajes de programación para integrar los datos y el código que opera en ellos, haciendo más fácil el modificar programas grandes. En la experiencia de laboratorio de hoy utilizarás una clase llamada Bird para practicar algunas de las destrezas básicas en C++ para la creación y manejo de objetos.

Objetivos:

  1. Crear objetos de una clase.
  2. Analizar la declaración de una clase para entender cómo crear y manipular objetos de esa clase.
  3. Analizar la declaración de una clase para entender cómo crear y manipular objetos de esa clase.
  4. Practicar la creación y manipulación de objetos, y la invocación de “setters” y “getters”.

Pre-Lab:

Antes de llegar al laboratorio debes:

  1. Haber repasado los siguientes conceptos:

a. creación de objetos de una clase.

b. utilización de métodos “getters” para acceder a los atributos de un objeto.

c. utilización de métodos “setters” para modificar los atributos de un objeto.

  1. Haber estudiado la documentación de la clase Bird disponible en este enlace.

  2. Haber estudiado los conceptos e instrucciones para la sesión de laboratorio.

  3. Haber tomado el quiz Pre-Lab que se encuentra en Moodle.



Clases y objetos en C++

Un objeto es un ente que contiene datos y procedimientos para manipularlos. Al igual que cada variable tiene un tipo de dato asociada a ella, cada objeto tiene una clase asociada que describe las propiedades de los objetos: sus datos (atributos), y los procedimientos con los que se pueden manipular los datos (métodos).

Para definir y utilizar un objeto no hay que saber todos los detalles de los métodos del objeto pero hay que saber cómo crearlo, y cómo interactuar con él. La información necesaria está disponible en la documentación de la clase. Antes de crear objetos de cualquier clase debemos familiarizarnos con su documentación. La documentación nos indica, entre otras cosas, que ente se está tratando de representar con la clase, y cuáles son los interfaces o métodos disponibles para manipular los objetos de la clase.

Dale un vistazo a la documentación de la clase Bird que se encuentra en http://ada.uprrp.edu/~ranazario/bird-html/class_bird.html.

Clases

Una clase es un pedazo de código en donde se describe cómo serán los objetos. Se definen las variables o atributos de los datos que contendrá el objeto y las funciones o métodos que hacen algún procedimiento a los datos del objeto. Para declarar una clase debemos especificar los tipos que tendrán las variables y los prototipos de los métodos de la clase.

Si no se especifica lo contrario, los atributos y métodos definidos en una clase serán “privados”. Esto quiere decir que esas variables solo se pueden acceder y cambiar por los métodos de la clase (constructores, “setters” y “getters”, entre otros).

Lo siguiente es el esqueleto de la declaración de una clase:


  class NombreClase
   {
    // Declaraciones

    private:
      // Declaraciones de variables o atributos y 
      // prototipos de métodos 
      // que sean privados para esta clase

      tipo varPrivada;
      tipo nombreMetodoPrivado(tipo de los parámetros);

    public:
      // Declaraciones de atributos y 
      // prototipos de métodos 
      // que sean públicos para todo el programa

      tipo varPública;
      tipo nombreMetodoPúblico(tipo de los parámetros);
   };

Puedes ver la declaración de la clase Bird en el archivo bird.h incluido en el programado de esta experiencia de laboratorio.

Objetos

Un objeto es un ente que contiene datos (al igual que una variable), llamados sus atributos, y también contiene procedimientos, llamados métodos, que se usan para manipularlos. Los objetos son “instancias” de una clase que se crean de manera similar a como se definen las variables:

NombreClase nombreObjeto;

Una vez creamos un objeto, podemos interaccionar con él usando los métodos de la clase a la que pertenece.

Métodos de una clase

Los métodos de una clase determinan qué acciones podemos tomar sobre los objetos de esa clase. Los métodos son parecidos a las funciones en el sentido de que pueden recibir parámetros y regresar un resultado. Una forma elemental de conocer los métodos de una clase es leyendo la declaración de la clase. Por ejemplo, lo siguiente es parte de la declaración de la clase Bird en el archivo bird.h.


class Bird : public QWidget
{
.
.
.
    Bird(int , EyeBrowType , QString , QString, QWidget *parent = 0) ;
    
    int getSize() const;
    EyeBrowType getEyebrow() const ;
    QString  getFaceColor() const;
    QString  getEyeColor() const;
    Qt::GlobalColor getColor(QString) const;

    void setSize(int) ;
    void setEyebrow(EyeBrowType) ;
    void setFaceColor(QString) ;
    void setEyeColor(QString) ;
.
.
.
};

Una vez creado un objeto, sus métodos proveen la única forma de cambiar sus atributos u obtener información o cómputos de los mismos. Es por esto que comúnmente se llama interface al conjunto de métodos de una clase. Los métodos son el interface entre el usuario de un objeto y su contenido.

En general, en cada clase se definen los prototipos de los métodos para construir los objetos, y para buscar, manipular y guardar los datos. Lo siguiente es el formato general del prototipo de un método:

tipoDevolver nombreMetodo(tipo de los parámetros);

Luego, en el código del proyecto se escribe la función correspondiente al método, comenzando con un encabezado que incluye el nombre de la clase a la cuál pertenece la función:

TipoDevolver NombreClase::NombreMetodo(parámetros)

Para que los objetos que sean instancia de una clase puedan tener acceso a las variables privadas de la clase se declaran métodos que sean públicos y que den acceso a estas clases (ver abajo “setters” y “getters”). Es preferible utilizar variables privadas y accederlas mediante los “setters” y “getters”, a declararlas públicas ya que de esta manera el objeto que está asociado a estas variables tiene el control de los cambios que se hacen.

Para invocar un método escribimos el nombre del objeto, seguido de un punto y luego el nombre del método:

nombreObjeto.nombreMetodo(argumentos);

Constructores

Los primeros métodos de una clase que debemos entender son los constructores.Una clase puede tener múltiples constructores. Uno de los constructores será invocado automáticamente cada vez que se crea un objeto de esa clase. En la mayoría de los casos, los constructores se utilizan para inicializar los valores de los atributos del objeto. Para poder crear objetos de una clase, debemos conocer cuáles son sus constructores.

En C++, los constructores tienen el mismo nombre que la clase. No se declara el tipo que devuelven porque estas funciones no devuelven ningún valor. Su declaración (incluida en la definición de la clase) es algo así:

nombreMetodo(tipo de los parámetros);

El encabezado de la función será algo así:

NombreClase::NombreMetodo(parámetros)

La clase Bird que estarás usando en la sesión de hoy tiene dos constructores (funciones sobrecargadas):

Bird (QWidget *parent=0)

Bird (int, EyeBrowType, QString, QString, QWidget *parent=0)

Puedes ver las declaraciones de los prototipos de estos métodos en la declaración de la clase Bird en el archivo bird.h del proyecto. La documentación se encuentra en http://ada.uprrp.edu/~ranazario/bird-html/class_bird.html. El primer constructor, Bird (QWidget *parent=0), es un método que se puede invocar con uno o ningún argumento. Si al invocarlo no se usa argumento, el parámetro de la función toma el valor 0.

El constructor de una clase que se puede invocar sin usar argumentos es el constructordefault” de la clase; esto es, el constructor que se invoca cuando creamos un objeto usando una instrucción como:

Bird pitirre;

Puedes ver las implementaciones de los métodos de la clase Birden el archivo bird.cpp. Nota que el primer constructor, Bird (QWidget *parent=0), asignará valores aleatorios (“random”) a cada uno de los atributos del objeto. Más adelante hay una breve explicación de la función randInt.

Dale un vistazo a la documentación del segundo constructor, Bird (int, EyeBrowType, QString, QString, QWidget *parent=0). Esta función requiere cuatro argumentos y tiene un quinto argumento que es opcional porque tiene un valor por defecto. Una manera para usar este constructor es creando un objeto como el siguiente:

Bird guaraguao(200, Bird::UPSET, "blue", "red");

“Setters” (“mutators”)

Las clases proveen métodos para modificar los valores de los atributos de un objeto que se ha creado. Estos métodos se llaman “setters” o “mutators”. Usualmente se declara un “setter” por cada atributo que tiene la clase. La clase Bird tiene los siguientes “setters”:

  • void setSize (int)
  • void setEyebrow (EyeBrowType)
  • void setFaceColor (QString)
  • void setEyeColor (QString)

Puedes ver las declaraciones de los métodos en la Figura 1 y en la declaración de la clase Bird en bird.h, y la implementación de algunos de los métodos en bird.cpp. El código en el siguiente ejemplo crea el objeto bobo de la clase Bird y luego cambia su tamaño a 333.

Bird bobo;
bobo.setSize(333);

“Getters” (“accessors”)

Las clases también proveen métodos para acceder (“get”) el valor del atributo de un objeto. Estos métodos se llaman “getters” o “accessors”. Usualmente se declara un “getter” por cada atributo que tiene la clase. La clase Bird tiene los siguientes “getters”:

  • int getSize ()
  • EyeBrowType getEyebrow ()
  • QString getFaceColor ()
  • QString getEyeColor ()

Puedes ver las declaraciones de los métodos en la Figura 1 y en la declaración de la clase Bird en bird.h, y las implementaciones de algunos de métodos en bird.cpp. El código en el siguiente ejemplo crea el objeto piolin de la clase Bird e imprime su tamaño.

Bird piolin;
cout << piolin.getSize();

Otras funciones o métodos que utilizarás en esta experiencia de laboratorio

MainWindow: El archivo mainwindow.h contiene la declaración de una clase llamada MainWindow. Los objetos que sean instancias de esta clase podrán utilizar los métodos sobrecargados

void MainWindow::addBird(int x, int y, Bird &b)

void MainWindow::addBird(Bird &b)

que añadirán a la pantalla un dibujo del objeto de la clase Bird que es recibido como argumento. El código en el siguiente ejemplo crea un objeto w de la clase MainWindow, crea un objeto zumbador de la clase Bird y lo añade a la posición (200,200) de la pantalla w usando el primer método.

MainWindow w;
Bird zumbador;
w.addBird(200,200,zumbador);

figure1.png

Figura 1. Ventana w con la imagen del objeto zumbador en la posición (200, 200).


¡Importante! No es suficiente solo crear los objetos Bird para que éstos aparezcan en la pantalla. Es necesario usar uno de los métodos addBird para que el dibujo aparezca en la pantalla.

randInt: La clase Bird incluye el método

int Bird::randInt(int min, int max)

para generar números enteros aleatorios (“random”) en el rango [min, max]. El método randInt depende de otra función para generar números aleatorios que requiere un primer elemento o semilla para ser evaluada. En este proyecto, ese primer elemento se genera con la invocación srand(time(NULL)) ;.



Sesión de laboratorio:

En la experiencia de laboratorio de hoy utilizarás la clase Bird para practicar la creación de objetos, acceder y cambiar sus atributos.

Ejercicio 1

En este ejercicio te familiarizarás con la clase Bird y con algunos métodos asociados a la clase MainWindow que define la ventana en donde se despliegan resultados.

Instrucciones

  1. Carga a Qt el proyecto Birds haciendo doble “click” en el archivo Birds.pro que se encuentra en la carpeta Documents/eip/Objects-Birds de tu computadora. También puedes ir a http://bitbucket.org/eip-uprrp/objects-birds para descargar la carpeta Objects-Birds a tu computadora.

  2. Estudia la clase Bird contenida en el archivo bird.h. Identifica los métodos que son constructores, “setters” y “getters”.

  3. En el archivo main.cpp (en Sources) la función main hace lo siguiente:

a. Crea un objeto aplicación de Qt, llamado a. Lo único que necesitas saber sobre este objeto es que gracias a él es que podemos crear una aplicación gráfica en Qt e interaccionar con ella.

b. Crea un objeto de la clase MainWindow llamado w. Este objeto corresponde a la ventana que verás cuando corras la aplicación.

c. Inicializa la semilla del generador de números aleatorios de Qt. Esto hará que los pájaros nuevos tengan tamaños, colores y cejas aleatorias (a menos que los forcemos a tener valores específicos).

d. Invoca el método show() al objeto w. Esto logra que se muestre la ventana donde se desplegarán los resultados.

e. En los programas que no tienen interfaz gráfica, la función main() usualmente termina con la instrucción return 0;. En este proyecto se utiliza la instrucción return a.exec(); para que el objeto a se haga cargo de la aplicación a partir de ese momento.

  1. Ejecuta el programa marcando la flecha verde en el menú de la izquierda de la ventana de Qt Creator. El programa debe mostrar una ventana blanca.

Ejercicio 2

En este ejercicio crearás objetos del tipo Bird usando el constructor por defecto y usando constructores donde defines características específicas para el objeto. También practicarás el uso de “getters” y “setters” para obtener y asignar atributos a los objetos.

Instrucciones

  1. Ahora crea un objeto de clase Bird llamado abelardo usando el constructor default y añádelo a la ventana w usando el método addBird(int x, int y, Bird b). Recuerda que la invocación del método debe comenzar con el nombre del objeto w y un punto.

  2. Corre varias veces el programa y maravíllate al ver a abelardo tener tamaños, colores y cejas distintas.

  3. Utiliza los “setters” setSize(int size), setFaceColor(Qstring color), setEyeColor(Qstring color), y setEyebrow(EyeBrowType) para que abelardo luzca como en la Figura 2 (su size es 200).


figure2.png

Figura 2. Abelardo.


  1. Crea otro objeto de la clase Bird llamado piolin que tenga cara azul, ojos verdes, y cejas UNI invocando el constructor Bird(int size, EyeBrowType brow, QString faceColor, QString eyeColor, QWidget *parent = 0). Su tamaño debe ser la mitad que el de abelardo. Añádelo a la misma ventana donde se muestra a abelardo usando w.addBird(300, 100, piolin) para obtener una imagen como la que se muestra en la Figura 3

figure3.png

Figura 3. Abelardo y Piolin.


  1. Crea otros dos objetos llamados juana y alondra que salgan dibujados en las coordenadas (100, 300) y (300,300) respectivamente. Crea a juana usando el constructor por defecto para que sus propiedades sean asignadas de forma aleatoria. Luego crea a alondra usando el otro constructor (el que recibe argumentos) para que puedas especificar sus propiedades durante su creación. alondra debe ser igual de grande que juana, tener el mismo tipo de cejas, y el mismo color de ojos. Su cara debe ser blanca. Añade a alondra y a juana a la misma ventana de abelardo y piolin. La ventana debe ser similar a la de la Figura 4.

figure4.png

Figura 4. Abelardo, Piolín, Juana y Alondra.


  1. Corre varias veces el programa para asegurarte que alondra y juana siguen pareciéndose en tamaño, cejas y ojos.


Entregas

Utiliza “Entrega” en Moodle para entregar el archivo main.cpp que contiene las invocaciones y cambios que hiciste al programa. Recuerda utilizar buenas prácticas de programación, incluir el nombre de los programadores y documentar tu programa.



Referencias

https://sites.google.com/a/wellesley.edu/wellesley-cs118-spring13/lectures-labs/lab-2




English | Español

Using Objects in C++ - Birds

main1.png main2.png main3.png

LAS IMAGENES DE ARRIBA NO SON LAS DE ESTE LAB SON LAS DEL LAB DE CONDICIONALES (USANDO OTRA VERSION DE BIRDS, BIRTH OF A BIRD). LAS IMAGENES ERAN LAS DE ABAJO

Up to now we’ve seen how to use variables to store and manipulate data of certain types and how to structure programs by dividing their tasks into functions. An object is an entity that it is used in many programming languages to integrate the data and the code that operates on it, simplifying the modification of large programs. In today’s laboratory experience you will use a class called Bird to practice some basic skills in C++ to create and manipulate objects.

Objectives:

  1. Create objects from a class.
  2. Manipulate attributes of the objects using their “getter” and “setter” method functions.

Pre-Lab:

Before the lab session each student should have:

  1. Reviewed the following concepts:

a. the creation of objects of a class.

b. using the “getter” method functions to access the attributes of an object.

c. using the “setter” method functions to modify the attributes of an object.

  1. Studied the documentation for the class Bird available in this link.

  2. Studied the concepts and instructions for the laboratory session.

  3. Taken the Pre-Lab quiz that can be found in Moodle.



Classes and objects in C++

An object es an entity that contains data and procedures to manipulate them. Similar to how each variable has a type of data associated to it, each object has a class associated that describes the properties of the objects: its data (attributes), and the procedures that can be used to manipulate its data (methods).

To define and use an object it is not necessary to know all of the details about the methods of the object, but you must know how to create it and how to interact with it. The necessary information is available in the class’ documentation. Before creating objects of any class we should familiarize ourselves with its documentation. The documentation indicates, among other things, what entity is trying to be represented in the class, and its interface or methods available to manipulate the objects of the class.

Take a look at the documentation of the Bird class which can be found in this link..

Classes

A class is a piece of code that describes how objects will be. The variables or data’s attributes that the object will contain are defined, and the methods that carry out a procedure on the object’s data. To declare a class we should specify the types that the variables and the prototypes of the methods will have.

If it isn’t specified otherwise, the attributes and methods defined in a class will be private. This means that the variables can only be accessed and changed by the methods of the class (constructors, setters, and getters, among others).

The following is the skeleton of the declaration of a class:


  class ClassName
   {
    // Declarations

    private:
      // Declaration of variables or attributes
      // and prototype member functions
      // that are private for this class

      type privateVar
      type nameOfPrivateMemFunc(type of the parameters);

    public:
      // Declarations of attributes
      // and prototypes of method functions
      // that are public for the entire program

      type publicVar;
      type nameOfPublicMemFunc(type of the parameters);
   };

You can see the declaration of the Bird class in the file bird.h included in this laboratory experience’s program.

Objects

An object is an entity that contains data (as well as a variable), called its attributes, and also contain procedures, called method, that are used to manipulate them. The objects are “instances” of a class that are created in a similar manner as how variables are defined:

ClassName objectName;

By creating an object we have available the methods of the class that the object belongs to.

Methods of a class

The methods of a class determine the actions that we can take on the objects of that class. The methods are similar to functions in the sense that they can receive parameters and return a result. An elementary way to know the methods of a class is reading de class declaration. For example, the following is a section of the declaration of the class Bird in the file bird.h.


class Bird : public QWidget
{
.
.
.
    Bird(int , EyeBrowType , QString , QString, QWidget *parent = 0) ;
    
    int getSize() const;
    EyeBrowType getEyebrow() const ;
    QString  getFaceColor() const;
    QString  getEyeColor() const;
    Qt::GlobalColor getColor(QString) const;

    void setSize(int) ;
    void setEyebrow(EyeBrowType) ;
    void setFaceColor(QString) ;
    void setEyeColor(QString) ;
.
.
.
};

Once the object is created, its methods provide the only way to change its attributes, to obtain information about them, or to compute with them. This is why the set of methods is commonly called interface. The methods are the interface between the object’s user and its content.

In general, in each class the prototypes of the methods are defined to construct the objects, and to search, manipulate and store the data. The following is a general format of a method prototype:

typeReturned methodName(type of the parameters);

Afterwards, we write the corresponding function to the method in the project’s code, starting with a header that includes the name of the class that the function belongs to:

TypeReturned ClassName::MethodName(parameters)

We declare public methods within the class so that objects that are instances of a class have permission to access private variables (these are the setters and getters). It’s prefered to use private variables and access them through the setters and getters, instead of declaring them public since the object that is associated to these variables has control over the changes that are made.

To invoke a method we write the name of the object, followed by a period and then the name of the method:

objectName.methodName(arguments);

Constructors

The first methods of a class that we should understand are the constructors. A class can have multiple constructors. One of the constructors will be invoked automatically each time an object of that class is created. In most of the cases, the constructors are used to initialize the values for the object’s attributes. To create objects of a class, we must know which are the constructors of the class.

In C++, the constructors have the same name as the class. The type returned by these functions is not declared since they do not return any value. Their declaration (included in the definition of the class) is like this:

methodName(type of the parameters);

The function header will be like this:

ClassName::MethodName(parameters)

The class Bird that you will be using in today’s session has two constructors (overloaded functions):

Bird (QWidget *parent=0)

Bird (int, EyeBrowType, QString, QString, QWidget *parent=0)

You can see the declarations of the method prototypes in the declaration of the Bird class in the project’s bird.h file. The documentation can be found in this link. The first constructor, Bird (QWidget *parent=0), is a method that can be invoked with one or no argument. If no argument is used, the function’s parameter has a value of 0.

A class’ constructor that can be invoked without using an argument is the class’ default constructor; that is, the constructor that is invoked when we create an object using an instruction like:

Bird pitirre;

You can see the implementations of the class Bird in the file bird.cpp. Note that the first constructor, Bird (QWidget *parent=0), will assign random values to each of the object’s attributes. Later on there is a brief explanation for the randInt function.

Have a look at the documentation for the second constructor, Bird (int, EyeBrowType, QString, QString, QWidget *parent=0). This function requires four arguments and has a fifth argument that is optional since it has a default value. One way to use this constructor is creating an object like this:

Bird guaraguao(200, Bird::UPSET, "blue", "red");

Setters (mutators)

Classes provide methods to modify the values of the attributes of an objected that has been created. These methods are called setters or mutators. Usually, we declare one setter for each attribute that the class has. The Bird class has the following setters:

  • void setSize (int)
  • void setEyebrow (EyeBrowType)
  • void setFaceColor (QString)
  • void setEyeColor (QString)

You can see the method’s declarations in Figure 1 and in the Bird class declaration in bird.h, and the implementation of the some of the methods in bird.cpp. The code in the following example creates the object bobo of the Bird class and then changes its size to 333.

Bird bobo;
bobo.setSize(333);

Getters (accessors)

Classes also provide methods to access (get) the value of the attribute of an object. These methods are called getters or accessors. We usually declare one getter for each attribute a class has. The Bird class has the following getters:

  • int getSize ()
  • EyeBrowType getEyebrow ()
  • QString getFaceColor ()
  • QString getEyeColor ()

You can see the declarations of the methods in Figure 1 and in the Bird class declaration in bird.h, and the implementations of some of the methods in bird.cpp. The code in the following example creates the object piolin of the Bird class and prints its size:

Bird piolin;
cout << piolin.getSize();

Other functions or methods you will use in this laboratory experience

MainWindow: The file mainwindow.h contains the declaration of a class called MainWindow. The objects that are instances of this class will be able to use the overloaded methods

void MainWindow::addBird(int x, int y, Bird &b)

void MainWindow::addBird(Bird &b)

that will add to the screen a drawing of an object of the Bird class that is received as an argument. The code in the following example creates an object w of the MainWindow class, creates an object zumbador of the Bird class and adds it in the position (200,200) on the screen w using the first method.

MainWindow w;
Bird zumbador;
w.addBird(200,200,zumbador);

figure1.png

Figure 1. Window w with the image of the object zumbador in the position (200,200).


Important! It’s not enough to just create the Bird objects so that these appear on the screen. It’s necessary to use one of the addBird methods to make the drawing appear on the screen.

randInt: The Bird class includes the method

int Bird::randInt(int min, int max)

to generate random numbers in the range [min, max]. The method randInt depends on another function to generate random numbers that require a first element or seed to be evaluated. In this project, that first element is generated with the function call srand(time(NULL)) ;.



Laboratory session:

In today’s laboratory experience you will use the Bird class to practice the creation of objects, accessing and changing its attributes.

Exercise 1

In this exercise you will familiarize yourself with the Bird class and with some methods associated with the MainWindow class that defines the window where the results are displayed.

Instructions

  1. Load the Birds project onto Qt by double clicking on the Birds.pro filein the directory Documents/eip/Objects-Birds of your computer. You may also go to http://bitbucket.org/eip-uprrp/objects-birds to download the Objects-Birds folder to your computer.

  2. Study the Bird class contained in the bird.h file. Identify the methods that are constructors, setters and getters.

  3. In the main.cpp file (in Sources) the main function does the following:

a. Creates a Qt object application, called a. The only thing you need to know is that thanks to this object we can create a graphical application in Qt and interact with it.

b. Creates an object of the MainWindow class called w. This object corresponds to the window that you will see when you run the application.

c. Initializes the seed of Qt’s random number generator. As a result of this, the new birds will have random sizes, colors and eyebrows (unless we force them to have specific values).

d. Invokes the method show() on the object w. This shows the window where the results will be displayed.

e. In programs that don’t have a graphical interface, the main() function usually ends with the instruction return 0;. In this project, the return a.exec(); instruction is used so that the object a takes charge of the application from that moment on.

  1. Execute the program by clicking on the green arrow in the left menu on the Qt Creator window. The program should display a blank window.

Exercise 2

In this exercise you will create an object of type Bird using the default constructor and using constructors where you define specific characteristics for the object. You will also practice the use of getters and setters to obtain and assign attributes to the objects.

Instructions

  1. Create an object of the Bird class called abelardo using the default constructor and add it to the w window using the method addBird(int x, int y, Bird b). Remember that the method’s call should start with the name of the object w and a period.

  2. Run the program several times and marvel at seeing abelardo have different sizes, colors and eyebrows.

  3. Use the setters setSize(int size), setFaceColor(Qstring color), setEyeColor(Qstring color), and setEyebrow(EyeBrowType) so that abelardo looks as in Figure 2 (its size is 200).


figure2.png

Figure 2. Abelardo.


  1. Create another object of class Bird called piolin that has a blue face, green eyes and UNI eyebrows invoking the constructor Bird(int size, EyeBrowType brow, QString faceColor, QString eyeColor, QWidget *parent = 0). Its size should be half of abelardo’s. Add it to the same window where abelardo is being displayed by using w.addBird(300, 100, piolin), to obtain an image like the one in Figure 3

figure3.png

Figure 3. Abelardo and Piolin.


  1. Create two other objects called juana and alondra that will appear drawn in the coordinates (100, 300) and (300,300) respectively. Create juana using the default constructor so that its properties are assigned randomly. Create alondra using the other constructor so that you may specify its properties during its creation. alondra should have the same size as juana, have the same type of eyebrows, and the same eye color. Its face should be white. Add alondra and juana to the window where abelardo and piolin are. The window should look similar to the one in Figure 4.

figure4.png

Figure 4. Abelardo, Piolin, Juana and Alondra.


  1. Run the program several times making sure that alondra and juana have the same size, eyebrows and eyes.


Deliverables

Use “Deliverables” in Moodle to hand in the main.cpp file that contains the function calls and changes you made to the program. Remember to use good programming techniques, include the name of the programmers involved, and document your program.



References

https://sites.google.com/a/wellesley.edu/wellesley-cs118-spring13/lectures-labs/lab-2