浏览代码

Splitted READMEs

root 8 年前
父节点
当前提交
c32893fed2
共有 3 个文件被更改,包括 735 次插入735 次删除
  1. 354
    0
      README-en.md
  2. 379
    0
      README-es.md
  3. 2
    735
      README.md

+ 354
- 0
README-en.md 查看文件

@@ -0,0 +1,354 @@
1
+
2
+# Using Objects in C++ - Birds
3
+
4
+
5
+![](images/headerBirds.png)
6
+
7
+<p> </p>
8
+
9
+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.
10
+
11
+
12
+
13
+##Objectives:
14
+
15
+1. Create objects from a class.
16
+2. Manipulate attributes of the objects using their "getter" and "setter" method functions.
17
+
18
+
19
+##Pre-Lab:
20
+
21
+Before the lab session each student should have:
22
+
23
+1. Reviewed the following concepts:
24
+
25
+  a. the creation of objects of a class.
26
+
27
+  b. using the "getter" method functions to access the attributes of an object.
28
+
29
+  c. using the "setter" method functions to modify the attributes of an object.
30
+
31
+2. Studied the documentation for the class `Bird` available in the documentation for this project (`eip/objetcs-birds/doc/es/html/class_bird.html`).
32
+
33
+3. Studied the concepts and instructions for the laboratory session.
34
+
35
+4. Taken the Pre-Lab quiz that can be found in Moodle.
36
+
37
+---
38
+
39
+---
40
+
41
+
42
+##Classes and objects in C++
43
+
44
+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*).
45
+
46
+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.
47
+
48
+Take a look at the documentation for the `Bird` class which can be found in the documentation for this project (`eip/objetcs-birds/doc/es/html/class_bird.html`).
49
+
50
+###Classes
51
+
52
+A class is a template for the creation of objects that establishes its attributes and behavior. 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).
53
+
54
+The following is the skeleton of the declaration of a class:
55
+
56
+---
57
+
58
+```cpp
59
+
60
+  class ClassName
61
+   {
62
+    // Declarations
63
+
64
+    private:
65
+      // Declaration of variables or attributes
66
+      // and prototype member functions
67
+      // that are private for this class
68
+
69
+      type privateVar
70
+      type nameOfPrivateMemFunc(type of the parameters);
71
+
72
+    public:
73
+      // Declarations of attributes
74
+      // and prototypes of method functions
75
+      // that are public for the entire program
76
+
77
+      type publicVar;
78
+      type nameOfPublicMemFunc(type of the parameters);
79
+   };
80
+```
81
+
82
+---
83
+
84
+You can see the declaration of the `Bird` class in the file `bird.h` included in this laboratory experience's program.
85
+
86
+###Objects
87
+
88
+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, with the exception that in some occasions we have to add values for the parameters:
89
+
90
+`ClassName objectName(arguments);`
91
+
92
+The creation  of the objects is done by functions called `constructors` that will be explained later. By creating an object we have available the methods of the class that the object belongs to.
93
+
94
+###Methods of a class
95
+
96
+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`.
97
+
98
+---
99
+
100
+
101
+```cpp
102
+
103
+class Bird : public QWidget
104
+{
105
+
106
+//...
107
+
108
+    Bird(int , EyeBrowType , QString , QString, QWidget *parent = 0) ;
109
+
110
+    int getSize() const;
111
+    EyeBrowType getEyebrow() const ;
112
+    QString  getFaceColor() const;
113
+    QString  getEyeColor() const;
114
+    Qt::GlobalColor getColor(QString) const;
115
+
116
+    void setSize(int) ;
117
+    void setEyebrow(EyeBrowType) ;
118
+    void setFaceColor(QString) ;
119
+    void setEyeColor(QString) ;
120
+
121
+//...
122
+
123
+};
124
+```
125
+
126
+
127
+---
128
+
129
+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.
130
+
131
+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:
132
+
133
+`typeReturned methodName(type of the parameters);`
134
+
135
+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:
136
+
137
+`TypeReturned ClassName::MethodName(parameters)`
138
+
139
+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.
140
+
141
+To invoke a method we write the name of the object, followed by a period and then the name of the method:
142
+
143
+`objectName.methodName(arguments);`
144
+
145
+
146
+####Constructors
147
+
148
+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.
149
+
150
+
151
+
152
+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:
153
+
154
+`methodName(type of the parameters);`
155
+
156
+The function header will be like this:
157
+
158
+`ClassName::MethodName(parameters)`
159
+
160
+The class `Bird` that you will be using in today's session has two constructors (overloaded functions):
161
+
162
+`Bird (QWidget *parent=0)`
163
+
164
+`Bird (int, EyeBrowType, QString, QString, QWidget *parent=0)`
165
+
166
+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 for the class can be found in the documentation for this project (`eip/objetcs-birds/doc/es/html/class_bird.html`). 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.
167
+
168
+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:
169
+
170
+`Bird pitirre;`
171
+
172
+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.
173
+
174
+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:
175
+
176
+`Bird guaraguao(200, Bird::UPSET, "blue", "red");`
177
+
178
+
179
+####Setters (mutators)
180
+
181
+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:
182
+
183
+* `void setSize (int)`
184
+* `void setEyebrow (EyeBrowType)`
185
+* `void setFaceColor (QString)`
186
+* `void setEyeColor (QString)`
187
+
188
+
189
+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.
190
+
191
+```
192
+Bird bobo;
193
+bobo.setSize(333);
194
+```
195
+
196
+####Getters (accessors)
197
+
198
+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:
199
+
200
+* `int getSize ()`
201
+* `EyeBrowType getEyebrow ()`
202
+* `QString  getFaceColor ()`
203
+* `QString   getEyeColor ()`
204
+
205
+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:
206
+
207
+```
208
+Bird piolin;
209
+cout << piolin.getSize();
210
+```
211
+
212
+####Other functions or methods you will use in this laboratory experience
213
+
214
+**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
215
+
216
+`void MainWindow::addBird(int x, int y, Bird &b)`  
217
+
218
+`void MainWindow::addBird(Bird &b)`  
219
+
220
+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.
221
+
222
+```cpp
223
+
224
+MainWindow w;
225
+Bird zumbador;
226
+w.addBird(200,200,zumbador);
227
+```
228
+
229
+
230
+---
231
+
232
+![figure1.png](images/figure1.png)
233
+
234
+**Figure 1.** Window `w` with the image of the object `zumbador` in the position (200,200).
235
+
236
+
237
+---
238
+
239
+
240
+
241
+**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.
242
+
243
+**randInt:** The `Bird` class includes the method
244
+
245
+`int Bird::randInt(int min, int max)`
246
+
247
+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)) ;`.
248
+
249
+
250
+---
251
+
252
+---
253
+
254
+!INCLUDE "../../eip-diagnostic/birds-objects/en/diag-birds-objects-01.html"
255
+
256
+!INCLUDE "../../eip-diagnostic/birds-objects/en/diag-birds-objects-02.html"
257
+
258
+!INCLUDE "../../eip-diagnostic/birds-objects/en/diag-birds-objects-03.html"
259
+
260
+!INCLUDE "../../eip-diagnostic/birds-objects/en/diag-birds-objects-04.html"
261
+
262
+!INCLUDE "../../eip-diagnostic/birds-objects/en/diag-birds-objects-05.html"
263
+
264
+---
265
+
266
+---
267
+
268
+
269
+##Laboratory session:
270
+
271
+In today's laboratory experience you will use the `Bird` class to practice the creation of objects, accessing and changing its attributes.
272
+
273
+###Exercise 1: Study the `Bird` class
274
+
275
+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.
276
+
277
+**Instructions**
278
+
279
+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.
280
+
281
+2. Study the `Bird` class contained in the `bird.h` file. Identify the methods that are constructors, setters and getters.
282
+
283
+3. In the `main.cpp` file (in Sources) the `main` function does the following:
284
+
285
+    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.
286
+
287
+    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.
288
+
289
+    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).
290
+
291
+    d. Invokes the method `show()` on the object `w`. This shows the window where the results will be displayed.
292
+
293
+    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.
294
+
295
+4. 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.
296
+
297
+###Exercise 2: Create objects of the `Bird` class with certain attributes
298
+
299
+In this exercise you will create objects of the  `Bird` class 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.
300
+
301
+**Instructions**
302
+
303
+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.
304
+
305
+2. Run the program several  times and marvel at seeing `abelardo` have different sizes, colors and eyebrows.
306
+
307
+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).
308
+
309
+  ---
310
+
311
+  ![figure2.png](images/figure2.png)
312
+
313
+  **Figure 2.** Abelardo.
314
+
315
+  ---
316
+
317
+4. 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
318
+
319
+  ---
320
+
321
+  ![figure3.png](images/figure3.png)
322
+
323
+  **Figure 3.** Abelardo and Piolin.
324
+
325
+  ---
326
+
327
+5. 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.
328
+
329
+  ---
330
+
331
+  ![figure4.png](images/figure4.png)
332
+
333
+  **Figure 4.** Abelardo, Piolin, Juana and Alondra.
334
+
335
+  ---
336
+
337
+6. Run the program several times making sure that `alondra` and `juana` have the same size, eyebrows and eyes.
338
+
339
+---
340
+
341
+---
342
+
343
+##Deliverables
344
+
345
+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.
346
+
347
+---
348
+
349
+---
350
+
351
+##References
352
+
353
+
354
+https://sites.google.com/a/wellesley.edu/wellesley-cs118-spring13/lectures-labs/lab-2

+ 379
- 0
README-es.md 查看文件

@@ -0,0 +1,379 @@
1
+
2
+#Utilizando objetos en C++ - Pájaros
3
+
4
+
5
+
6
+![](images/headerBirds.png)
7
+
8
+<p> </p>
9
+
10
+[version 2016.02.10]
11
+
12
+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.
13
+
14
+##Objetivos:
15
+
16
+1. Crear objetos de una clase.
17
+2. Analizar la declaración de una clase para entender cómo crear y manipular objetos de esa clase.
18
+3. Analizar la declaración de una clase para entender cómo crear y manipular objetos de esa clase.
19
+4. Practicar la creación y manipulación de objetos, y la invocación de "setters" y "getters".
20
+
21
+
22
+
23
+
24
+##Pre-Lab:
25
+
26
+Antes de llegar al laboratorio debes:
27
+
28
+1. Haber repasado los siguientes conceptos:
29
+
30
+    a. creación de objetos de una clase.
31
+
32
+    b. utilización de métodos "getters" para acceder a los atributos de un objeto.
33
+
34
+    c. utilización de métodos "setters" para modificar los atributos de un objeto.
35
+  
36
+
37
+2. Haber estudiado la documentación de la clase `Bird` disponible dentro de la documentación del proyecto (`objetcs-birds/doc/es/html/class_bird.html`).
38
+
39
+3. Haber estudiado los conceptos e instrucciones para la sesión de laboratorio.
40
+
41
+
42
+
43
+---
44
+
45
+---
46
+
47
+
48
+##Clases y objetos en C++
49
+
50
+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:
51
+sus datos (*atributos*), y los procedimientos con los que se pueden manipular los datos (*métodos*).
52
+
53
+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.
54
+
55
+Una vez hayas bajado los archivos de este proyecto a tu computadora, dale un vistazo a la documentación de la clase `Bird` que se encuentra dentro de la documentación del proyecto (`objetcs-birds/doc/es/html/class_bird.html`).
56
+
57
+###Clases
58
+
59
+Una clase es una plantilla para la creación de objetos que establece sus atributos y su comportamiento. 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).
60
+
61
+Lo siguiente es el esqueleto de la declaración de una clase:
62
+
63
+---
64
+
65
+```cpp
66
+  class NombreClase
67
+   {
68
+    // Declaraciones
69
+
70
+    private:
71
+      // Declaraciones de variables o atributos y
72
+      // prototipos de métodos
73
+      // que sean privados para esta clase
74
+
75
+      tipo varPrivada;
76
+      tipo nombreMetodoPrivado(tipo de los parámetros);
77
+
78
+    public:
79
+      // Declaraciones de atributos y
80
+      // prototipos de métodos
81
+      // que sean públicos para todo el programa
82
+
83
+      tipo varPública;
84
+      tipo nombreMetodoPúblico(tipo de los parámetros);
85
+   };
86
+```
87
+---
88
+
89
+Puedes ver la declaración de la clase `Bird` en el archivo `bird.h` incluido en el programado de esta experiencia de laboratorio.
90
+
91
+###Objetos
92
+
93
+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, con la excepción de que en ocasiones hay que añadir valores para los parámetros:
94
+
95
+`NombreClase nombreObjeto(argumentos);`
96
+
97
+La creación de los objetos la hacen unas funciones llamadas `constructores` que explicaremos más adelante. Una vez creamos un objeto, podemos interaccionar con él usando los métodos de la clase a la que pertenece.
98
+
99
+###Métodos de una clase
100
+
101
+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`.
102
+
103
+---
104
+
105
+
106
+```cpp
107
+
108
+class Bird : public QWidget
109
+{
110
+
111
+//...
112
+
113
+    Bird(int , EyeBrowType , QString , QString, QWidget *parent = 0) ;
114
+
115
+    int getSize() const;
116
+    EyeBrowType getEyebrow() const ;
117
+    QString  getFaceColor() const;
118
+    QString  getEyeColor() const;
119
+    Qt::GlobalColor getColor(QString) const;
120
+
121
+    void setSize(int) ;
122
+    void setEyebrow(EyeBrowType) ;
123
+    void setFaceColor(QString) ;
124
+    void setEyeColor(QString) ;
125
+
126
+//...
127
+
128
+};
129
+```
130
+---
131
+
132
+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.
133
+
134
+
135
+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:
136
+
137
+`tipoDevolver nombreMetodo(tipo de los parámetros);`
138
+
139
+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:
140
+
141
+`TipoDevolver NombreClase::NombreMetodo(parámetros)`
142
+
143
+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.
144
+
145
+Para invocar un método escribimos el nombre del objeto, seguido de un punto y luego el nombre del método:
146
+
147
+`nombreObjeto.nombreMetodo(argumentos);`
148
+
149
+
150
+
151
+####Constructores
152
+
153
+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.
154
+
155
+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í:
156
+
157
+`nombreMetodo(tipo de los parámetros);`
158
+
159
+El encabezado de la función será algo así:
160
+
161
+`NombreClase::NombreMetodo(parámetros)`
162
+
163
+La clase `Bird` que estarás usando en la sesión de hoy tiene dos constructores (funciones sobrecargadas):
164
+
165
+`Bird (QWidget *parent=0)`
166
+
167
+`Bird (int, EyeBrowType, QString, QString, QWidget *parent=0)`
168
+
169
+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 de la clase se encuentra dentro de la documentación del proyecto (`eip/objetcs-birds/doc/es/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.
170
+
171
+El constructor de una clase que se puede invocar sin usar argumentos es el *constructor* "*default*" de la clase; esto es, el constructor que se invoca cuando creamos un objeto usando una instrucción como:
172
+
173
+`Bird pitirre;`
174
+
175
+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`.
176
+
177
+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:
178
+
179
+`Bird guaraguao(200, Bird::UPSET, "blue", "red");`
180
+
181
+
182
+####"Setters" ("mutators")
183
+
184
+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":
185
+
186
+* `void setSize (int)`
187
+* `void setEyebrow (EyeBrowType)`
188
+* `void setFaceColor (QString)`
189
+* `void setEyeColor (QString)`
190
+
191
+
192
+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.
193
+
194
+```
195
+Bird bobo;
196
+bobo.setSize(333);
197
+```
198
+
199
+
200
+####"Getters" ("accessors")
201
+
202
+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":
203
+
204
+* `int getSize ()`
205
+* `EyeBrowType getEyebrow ()`
206
+* `QString  getFaceColor ()`
207
+* `QString   getEyeColor ()`
208
+
209
+
210
+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.
211
+
212
+```
213
+Bird piolin;
214
+cout << piolin.getSize();
215
+```
216
+
217
+####Otras funciones o métodos que utilizarás en esta experiencia de laboratorio
218
+
219
+**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
220
+
221
+`void MainWindow::addBird(int x, int y, Bird &b)`  
222
+
223
+`void MainWindow::addBird(Bird &b)`
224
+
225
+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.
226
+
227
+
228
+
229
+```cpp
230
+
231
+MainWindow w;
232
+Bird zumbador;
233
+w.addBird(200,200,zumbador);
234
+```
235
+
236
+
237
+---
238
+
239
+![figure1.png](images/figure1.png)
240
+
241
+**Figura 1.** Ventana `w` con la imagen del objeto `zumbador` en la posición (200, 200).
242
+
243
+
244
+---
245
+
246
+
247
+
248
+**¡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.
249
+
250
+
251
+**randInt:** La clase `Bird` incluye el método
252
+
253
+`int Bird::randInt(int min, int max)`
254
+
255
+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)) ;`.
256
+
257
+
258
+
259
+---
260
+
261
+---
262
+
263
+!INCLUDE "../../eip-diagnostic/birds-objects/es/diag-birds-objects-01.html"
264
+
265
+!INCLUDE "../../eip-diagnostic/birds-objects/es/diag-birds-objects-02.html"
266
+
267
+!INCLUDE "../../eip-diagnostic/birds-objects/es/diag-birds-objects-03.html"
268
+
269
+!INCLUDE "../../eip-diagnostic/birds-objects/es/diag-birds-objects-04.html"
270
+
271
+!INCLUDE "../../eip-diagnostic/birds-objects/es/diag-birds-objects-05.html"
272
+
273
+---
274
+
275
+---
276
+
277
+##Sesión de laboratorio:
278
+
279
+En la experiencia de laboratorio de hoy utilizarás la clase `Bird` para practicar la creación de objetos, acceder y cambiar sus atributos.
280
+
281
+
282
+###Ejercicio 1: Estudiar la clase `Bird`
283
+
284
+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.
285
+
286
+**Instrucciones**
287
+
288
+1. Descarga la carpeta `Objects-Birds` de `Bitbucket` usando un terminal, moviéndote al directorio `Documents/eip`,  y escribiendo el comando `git clone http://bitbucket.org/eip-uprrp/objects-birds`.
289
+
290
+2. 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. Configura el proyecto.
291
+
292
+3. Estudia la clase `Bird` contenida en el archivo `bird.h`. Identifica los métodos que son constructores, "setters" y "getters".
293
+
294
+4. En el archivo `main.cpp` (en Sources) la función `main` hace lo siguiente:
295
+
296
+    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.
297
+
298
+    b. Crea un objeto  de la clase MainWindow llamado `w`. Este objeto corresponde a la ventana que verás cuando corras la aplicación.
299
+
300
+    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).
301
+
302
+    d. Invoca el método `show()` al objeto `w`. Esto logra que se muestre la ventana donde se desplegarán los resultados.
303
+
304
+    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.
305
+
306
+5. 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.
307
+
308
+###Ejercicio 2: Crear objetos de clase `Bird` con ciertos atributos
309
+
310
+En este ejercicio crearás objetos de clase `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.
311
+
312
+**Instrucciones**
313
+
314
+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.
315
+
316
+2. Corre varias veces el programa y maravíllate al ver a `abelardo` tener tamaños, colores y cejas distintas.
317
+
318
+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).
319
+
320
+  ---
321
+
322
+  ![figure2.png](images/figure2.png)
323
+
324
+  **Figura 2.** Abelardo.
325
+
326
+  ---
327
+
328
+4. 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.
329
+
330
+   ---
331
+
332
+  ![figure3.png](images/figure3.png)
333
+
334
+  **Figura 3.** Abelardo y Piolin.
335
+
336
+  ---
337
+
338
+5. 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.
339
+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.
340
+
341
+   ---
342
+
343
+  ![figure4.png](images/figure4.png)
344
+
345
+  **Figura 4.** Abelardo, Piolín, Juana y Alondra.
346
+
347
+  ---
348
+
349
+6. Corre varias veces el programa para asegurarte que `alondra` y `juana` siguen pareciéndose en tamaño, cejas y ojos.
350
+
351
+
352
+---
353
+
354
+---
355
+
356
+##Entregas
357
+
358
+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.
359
+
360
+
361
+
362
+---
363
+
364
+---
365
+
366
+##Referencias
367
+
368
+
369
+https://sites.google.com/a/wellesley.edu/wellesley-cs118-spring13/lectures-labs/lab-2
370
+
371
+---
372
+
373
+---
374
+
375
+---
376
+
377
+
378
+
379
+

+ 2
- 735
README.md 查看文件

@@ -1,735 +1,2 @@
1
-[English](#markdown-header-using-objects-in-c-birds) | [Español](#markdown-header-utilizando-objetos-en-c-pajaros)
2
-
3
-#Utilizando objetos en C++ - Pájaros
4
-
5
-
6
-
7
-![](images/headerBirds.png)
8
-
9
-<p> </p>
10
-
11
-[version 2016.02.10]
12
-
13
-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.
14
-
15
-##Objetivos:
16
-
17
-1. Crear objetos de una clase.
18
-2. Analizar la declaración de una clase para entender cómo crear y manipular objetos de esa clase.
19
-3. Analizar la declaración de una clase para entender cómo crear y manipular objetos de esa clase.
20
-4. Practicar la creación y manipulación de objetos, y la invocación de "setters" y "getters".
21
-
22
-
23
-
24
-
25
-##Pre-Lab:
26
-
27
-Antes de llegar al laboratorio debes:
28
-
29
-1. Haber repasado los siguientes conceptos:
30
-
31
-    a. creación de objetos de una clase.
32
-
33
-    b. utilización de métodos "getters" para acceder a los atributos de un objeto.
34
-
35
-    c. utilización de métodos "setters" para modificar los atributos de un objeto.
36
-  
37
-
38
-2. Haber estudiado la documentación de la clase `Bird` disponible dentro de la documentación del proyecto (`objetcs-birds/doc/es/html/class_bird.html`).
39
-
40
-3. Haber estudiado los conceptos e instrucciones para la sesión de laboratorio.
41
-
42
-
43
-
44
----
45
-
46
----
47
-
48
-
49
-##Clases y objetos en C++
50
-
51
-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:
52
-sus datos (*atributos*), y los procedimientos con los que se pueden manipular los datos (*métodos*).
53
-
54
-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.
55
-
56
-Una vez hayas bajado los archivos de este proyecto a tu computadora, dale un vistazo a la documentación de la clase `Bird` que se encuentra dentro de la documentación del proyecto (`objetcs-birds/doc/es/html/class_bird.html`).
57
-
58
-###Clases
59
-
60
-Una clase es una plantilla para la creación de objetos que establece sus atributos y su comportamiento. 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).
61
-
62
-Lo siguiente es el esqueleto de la declaración de una clase:
63
-
64
----
65
-
66
-```cpp
67
-  class NombreClase
68
-   {
69
-    // Declaraciones
70
-
71
-    private:
72
-      // Declaraciones de variables o atributos y
73
-      // prototipos de métodos
74
-      // que sean privados para esta clase
75
-
76
-      tipo varPrivada;
77
-      tipo nombreMetodoPrivado(tipo de los parámetros);
78
-
79
-    public:
80
-      // Declaraciones de atributos y
81
-      // prototipos de métodos
82
-      // que sean públicos para todo el programa
83
-
84
-      tipo varPública;
85
-      tipo nombreMetodoPúblico(tipo de los parámetros);
86
-   };
87
-```
88
----
89
-
90
-Puedes ver la declaración de la clase `Bird` en el archivo `bird.h` incluido en el programado de esta experiencia de laboratorio.
91
-
92
-###Objetos
93
-
94
-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, con la excepción de que en ocasiones hay que añadir valores para los parámetros:
95
-
96
-`NombreClase nombreObjeto(argumentos);`
97
-
98
-La creación de los objetos la hacen unas funciones llamadas `constructores` que explicaremos más adelante. Una vez creamos un objeto, podemos interaccionar con él usando los métodos de la clase a la que pertenece.
99
-
100
-###Métodos de una clase
101
-
102
-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`.
103
-
104
----
105
-
106
-
107
-```cpp
108
-
109
-class Bird : public QWidget
110
-{
111
-
112
-//...
113
-
114
-    Bird(int , EyeBrowType , QString , QString, QWidget *parent = 0) ;
115
-
116
-    int getSize() const;
117
-    EyeBrowType getEyebrow() const ;
118
-    QString  getFaceColor() const;
119
-    QString  getEyeColor() const;
120
-    Qt::GlobalColor getColor(QString) const;
121
-
122
-    void setSize(int) ;
123
-    void setEyebrow(EyeBrowType) ;
124
-    void setFaceColor(QString) ;
125
-    void setEyeColor(QString) ;
126
-
127
-//...
128
-
129
-};
130
-```
131
----
132
-
133
-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.
134
-
135
-
136
-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:
137
-
138
-`tipoDevolver nombreMetodo(tipo de los parámetros);`
139
-
140
-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:
141
-
142
-`TipoDevolver NombreClase::NombreMetodo(parámetros)`
143
-
144
-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.
145
-
146
-Para invocar un método escribimos el nombre del objeto, seguido de un punto y luego el nombre del método:
147
-
148
-`nombreObjeto.nombreMetodo(argumentos);`
149
-
150
-
151
-
152
-####Constructores
153
-
154
-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.
155
-
156
-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í:
157
-
158
-`nombreMetodo(tipo de los parámetros);`
159
-
160
-El encabezado de la función será algo así:
161
-
162
-`NombreClase::NombreMetodo(parámetros)`
163
-
164
-La clase `Bird` que estarás usando en la sesión de hoy tiene dos constructores (funciones sobrecargadas):
165
-
166
-`Bird (QWidget *parent=0)`
167
-
168
-`Bird (int, EyeBrowType, QString, QString, QWidget *parent=0)`
169
-
170
-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 de la clase se encuentra dentro de la documentación del proyecto (`eip/objetcs-birds/doc/es/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.
171
-
172
-El constructor de una clase que se puede invocar sin usar argumentos es el *constructor* "*default*" de la clase; esto es, el constructor que se invoca cuando creamos un objeto usando una instrucción como:
173
-
174
-`Bird pitirre;`
175
-
176
-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`.
177
-
178
-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:
179
-
180
-`Bird guaraguao(200, Bird::UPSET, "blue", "red");`
181
-
182
-
183
-####"Setters" ("mutators")
184
-
185
-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":
186
-
187
-* `void setSize (int)`
188
-* `void setEyebrow (EyeBrowType)`
189
-* `void setFaceColor (QString)`
190
-* `void setEyeColor (QString)`
191
-
192
-
193
-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.
194
-
195
-```
196
-Bird bobo;
197
-bobo.setSize(333);
198
-```
199
-
200
-
201
-####"Getters" ("accessors")
202
-
203
-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":
204
-
205
-* `int getSize ()`
206
-* `EyeBrowType getEyebrow ()`
207
-* `QString  getFaceColor ()`
208
-* `QString   getEyeColor ()`
209
-
210
-
211
-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.
212
-
213
-```
214
-Bird piolin;
215
-cout << piolin.getSize();
216
-```
217
-
218
-####Otras funciones o métodos que utilizarás en esta experiencia de laboratorio
219
-
220
-**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
221
-
222
-`void MainWindow::addBird(int x, int y, Bird &b)`  
223
-
224
-`void MainWindow::addBird(Bird &b)`
225
-
226
-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.
227
-
228
-
229
-
230
-```cpp
231
-
232
-MainWindow w;
233
-Bird zumbador;
234
-w.addBird(200,200,zumbador);
235
-```
236
-
237
-
238
----
239
-
240
-![figure1.png](images/figure1.png)
241
-
242
-**Figura 1.** Ventana `w` con la imagen del objeto `zumbador` en la posición (200, 200).
243
-
244
-
245
----
246
-
247
-
248
-
249
-**¡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.
250
-
251
-
252
-**randInt:** La clase `Bird` incluye el método
253
-
254
-`int Bird::randInt(int min, int max)`
255
-
256
-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)) ;`.
257
-
258
-
259
-
260
----
261
-
262
----
263
-
264
-!INCLUDE "../../eip-diagnostic/birds-objects/es/diag-birds-objects-01.html"
265
-
266
-!INCLUDE "../../eip-diagnostic/birds-objects/es/diag-birds-objects-02.html"
267
-
268
-!INCLUDE "../../eip-diagnostic/birds-objects/es/diag-birds-objects-03.html"
269
-
270
-!INCLUDE "../../eip-diagnostic/birds-objects/es/diag-birds-objects-04.html"
271
-
272
-!INCLUDE "../../eip-diagnostic/birds-objects/es/diag-birds-objects-05.html"
273
-
274
----
275
-
276
----
277
-
278
-##Sesión de laboratorio:
279
-
280
-En la experiencia de laboratorio de hoy utilizarás la clase `Bird` para practicar la creación de objetos, acceder y cambiar sus atributos.
281
-
282
-
283
-###Ejercicio 1: Estudiar la clase `Bird`
284
-
285
-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.
286
-
287
-**Instrucciones**
288
-
289
-1. Descarga la carpeta `Objects-Birds` de `Bitbucket` usando un terminal, moviéndote al directorio `Documents/eip`,  y escribiendo el comando `git clone http://bitbucket.org/eip-uprrp/objects-birds`.
290
-
291
-2. 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. Configura el proyecto.
292
-
293
-3. Estudia la clase `Bird` contenida en el archivo `bird.h`. Identifica los métodos que son constructores, "setters" y "getters".
294
-
295
-4. En el archivo `main.cpp` (en Sources) la función `main` hace lo siguiente:
296
-
297
-    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.
298
-
299
-    b. Crea un objeto  de la clase MainWindow llamado `w`. Este objeto corresponde a la ventana que verás cuando corras la aplicación.
300
-
301
-    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).
302
-
303
-    d. Invoca el método `show()` al objeto `w`. Esto logra que se muestre la ventana donde se desplegarán los resultados.
304
-
305
-    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.
306
-
307
-5. 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.
308
-
309
-###Ejercicio 2: Crear objetos de clase `Bird` con ciertos atributos
310
-
311
-En este ejercicio crearás objetos de clase `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.
312
-
313
-**Instrucciones**
314
-
315
-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.
316
-
317
-2. Corre varias veces el programa y maravíllate al ver a `abelardo` tener tamaños, colores y cejas distintas.
318
-
319
-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).
320
-
321
-  ---
322
-
323
-  ![figure2.png](images/figure2.png)
324
-
325
-  **Figura 2.** Abelardo.
326
-
327
-  ---
328
-
329
-4. 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.
330
-
331
-   ---
332
-
333
-  ![figure3.png](images/figure3.png)
334
-
335
-  **Figura 3.** Abelardo y Piolin.
336
-
337
-  ---
338
-
339
-5. 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.
340
-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.
341
-
342
-   ---
343
-
344
-  ![figure4.png](images/figure4.png)
345
-
346
-  **Figura 4.** Abelardo, Piolín, Juana y Alondra.
347
-
348
-  ---
349
-
350
-6. Corre varias veces el programa para asegurarte que `alondra` y `juana` siguen pareciéndose en tamaño, cejas y ojos.
351
-
352
-
353
----
354
-
355
----
356
-
357
-##Entregas
358
-
359
-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.
360
-
361
-
362
-
363
----
364
-
365
----
366
-
367
-##Referencias
368
-
369
-
370
-https://sites.google.com/a/wellesley.edu/wellesley-cs118-spring13/lectures-labs/lab-2
371
-
372
----
373
-
374
----
375
-
376
----
377
-
378
-
379
-
380
-
381
-[English](#markdown-header-using-objects-in-c-birds) | [Español](#markdown-header-utilizando-objetos-en-c-pajaros)
382
-
383
-# Using Objects in C++ - Birds
384
-
385
-
386
-![](images/headerBirds.png)
387
-
388
-<p> </p>
389
-
390
-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.
391
-
392
-
393
-
394
-##Objectives:
395
-
396
-1. Create objects from a class.
397
-2. Manipulate attributes of the objects using their "getter" and "setter" method functions.
398
-
399
-
400
-##Pre-Lab:
401
-
402
-Before the lab session each student should have:
403
-
404
-1. Reviewed the following concepts:
405
-
406
-  a. the creation of objects of a class.
407
-
408
-  b. using the "getter" method functions to access the attributes of an object.
409
-
410
-  c. using the "setter" method functions to modify the attributes of an object.
411
-
412
-2. Studied the documentation for the class `Bird` available in the documentation for this project (`eip/objetcs-birds/doc/es/html/class_bird.html`).
413
-
414
-3. Studied the concepts and instructions for the laboratory session.
415
-
416
-4. Taken the Pre-Lab quiz that can be found in Moodle.
417
-
418
----
419
-
420
----
421
-
422
-
423
-##Classes and objects in C++
424
-
425
-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*).
426
-
427
-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.
428
-
429
-Take a look at the documentation for the `Bird` class which can be found in the documentation for this project (`eip/objetcs-birds/doc/es/html/class_bird.html`).
430
-
431
-###Classes
432
-
433
-A class is a template for the creation of objects that establishes its attributes and behavior. 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).
434
-
435
-The following is the skeleton of the declaration of a class:
436
-
437
----
438
-
439
-```cpp
440
-
441
-  class ClassName
442
-   {
443
-    // Declarations
444
-
445
-    private:
446
-      // Declaration of variables or attributes
447
-      // and prototype member functions
448
-      // that are private for this class
449
-
450
-      type privateVar
451
-      type nameOfPrivateMemFunc(type of the parameters);
452
-
453
-    public:
454
-      // Declarations of attributes
455
-      // and prototypes of method functions
456
-      // that are public for the entire program
457
-
458
-      type publicVar;
459
-      type nameOfPublicMemFunc(type of the parameters);
460
-   };
461
-```
462
-
463
----
464
-
465
-You can see the declaration of the `Bird` class in the file `bird.h` included in this laboratory experience's program.
466
-
467
-###Objects
468
-
469
-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, with the exception that in some occasions we have to add values for the parameters:
470
-
471
-`ClassName objectName(arguments);`
472
-
473
-The creation  of the objects is done by functions called `constructors` that will be explained later. By creating an object we have available the methods of the class that the object belongs to.
474
-
475
-###Methods of a class
476
-
477
-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`.
478
-
479
----
480
-
481
-
482
-```cpp
483
-
484
-class Bird : public QWidget
485
-{
486
-
487
-//...
488
-
489
-    Bird(int , EyeBrowType , QString , QString, QWidget *parent = 0) ;
490
-
491
-    int getSize() const;
492
-    EyeBrowType getEyebrow() const ;
493
-    QString  getFaceColor() const;
494
-    QString  getEyeColor() const;
495
-    Qt::GlobalColor getColor(QString) const;
496
-
497
-    void setSize(int) ;
498
-    void setEyebrow(EyeBrowType) ;
499
-    void setFaceColor(QString) ;
500
-    void setEyeColor(QString) ;
501
-
502
-//...
503
-
504
-};
505
-```
506
-
507
-
508
----
509
-
510
-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.
511
-
512
-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:
513
-
514
-`typeReturned methodName(type of the parameters);`
515
-
516
-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:
517
-
518
-`TypeReturned ClassName::MethodName(parameters)`
519
-
520
-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.
521
-
522
-To invoke a method we write the name of the object, followed by a period and then the name of the method:
523
-
524
-`objectName.methodName(arguments);`
525
-
526
-
527
-####Constructors
528
-
529
-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.
530
-
531
-
532
-
533
-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:
534
-
535
-`methodName(type of the parameters);`
536
-
537
-The function header will be like this:
538
-
539
-`ClassName::MethodName(parameters)`
540
-
541
-The class `Bird` that you will be using in today's session has two constructors (overloaded functions):
542
-
543
-`Bird (QWidget *parent=0)`
544
-
545
-`Bird (int, EyeBrowType, QString, QString, QWidget *parent=0)`
546
-
547
-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 for the class can be found in the documentation for this project (`eip/objetcs-birds/doc/es/html/class_bird.html`). 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.
548
-
549
-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:
550
-
551
-`Bird pitirre;`
552
-
553
-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.
554
-
555
-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:
556
-
557
-`Bird guaraguao(200, Bird::UPSET, "blue", "red");`
558
-
559
-
560
-####Setters (mutators)
561
-
562
-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:
563
-
564
-* `void setSize (int)`
565
-* `void setEyebrow (EyeBrowType)`
566
-* `void setFaceColor (QString)`
567
-* `void setEyeColor (QString)`
568
-
569
-
570
-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.
571
-
572
-```
573
-Bird bobo;
574
-bobo.setSize(333);
575
-```
576
-
577
-####Getters (accessors)
578
-
579
-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:
580
-
581
-* `int getSize ()`
582
-* `EyeBrowType getEyebrow ()`
583
-* `QString  getFaceColor ()`
584
-* `QString   getEyeColor ()`
585
-
586
-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:
587
-
588
-```
589
-Bird piolin;
590
-cout << piolin.getSize();
591
-```
592
-
593
-####Other functions or methods you will use in this laboratory experience
594
-
595
-**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
596
-
597
-`void MainWindow::addBird(int x, int y, Bird &b)`  
598
-
599
-`void MainWindow::addBird(Bird &b)`  
600
-
601
-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.
602
-
603
-```cpp
604
-
605
-MainWindow w;
606
-Bird zumbador;
607
-w.addBird(200,200,zumbador);
608
-```
609
-
610
-
611
----
612
-
613
-![figure1.png](images/figure1.png)
614
-
615
-**Figure 1.** Window `w` with the image of the object `zumbador` in the position (200,200).
616
-
617
-
618
----
619
-
620
-
621
-
622
-**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.
623
-
624
-**randInt:** The `Bird` class includes the method
625
-
626
-`int Bird::randInt(int min, int max)`
627
-
628
-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)) ;`.
629
-
630
-
631
----
632
-
633
----
634
-
635
-!INCLUDE "../../eip-diagnostic/birds-objects/en/diag-birds-objects-01.html"
636
-
637
-!INCLUDE "../../eip-diagnostic/birds-objects/en/diag-birds-objects-02.html"
638
-
639
-!INCLUDE "../../eip-diagnostic/birds-objects/en/diag-birds-objects-03.html"
640
-
641
-!INCLUDE "../../eip-diagnostic/birds-objects/en/diag-birds-objects-04.html"
642
-
643
-!INCLUDE "../../eip-diagnostic/birds-objects/en/diag-birds-objects-05.html"
644
-
645
----
646
-
647
----
648
-
649
-
650
-##Laboratory session:
651
-
652
-In today's laboratory experience you will use the `Bird` class to practice the creation of objects, accessing and changing its attributes.
653
-
654
-###Exercise 1: Study the `Bird` class
655
-
656
-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.
657
-
658
-**Instructions**
659
-
660
-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.
661
-
662
-2. Study the `Bird` class contained in the `bird.h` file. Identify the methods that are constructors, setters and getters.
663
-
664
-3. In the `main.cpp` file (in Sources) the `main` function does the following:
665
-
666
-    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.
667
-
668
-    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.
669
-
670
-    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).
671
-
672
-    d. Invokes the method `show()` on the object `w`. This shows the window where the results will be displayed.
673
-
674
-    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.
675
-
676
-4. 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.
677
-
678
-###Exercise 2: Create objects of the `Bird` class with certain attributes
679
-
680
-In this exercise you will create objects of the  `Bird` class 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.
681
-
682
-**Instructions**
683
-
684
-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.
685
-
686
-2. Run the program several  times and marvel at seeing `abelardo` have different sizes, colors and eyebrows.
687
-
688
-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).
689
-
690
-  ---
691
-
692
-  ![figure2.png](images/figure2.png)
693
-
694
-  **Figure 2.** Abelardo.
695
-
696
-  ---
697
-
698
-4. 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
699
-
700
-  ---
701
-
702
-  ![figure3.png](images/figure3.png)
703
-
704
-  **Figure 3.** Abelardo and Piolin.
705
-
706
-  ---
707
-
708
-5. 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.
709
-
710
-  ---
711
-
712
-  ![figure4.png](images/figure4.png)
713
-
714
-  **Figure 4.** Abelardo, Piolin, Juana and Alondra.
715
-
716
-  ---
717
-
718
-6. Run the program several times making sure that `alondra` and `juana` have the same size, eyebrows and eyes.
719
-
720
----
721
-
722
----
723
-
724
-##Deliverables
725
-
726
-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.
727
-
728
----
729
-
730
----
731
-
732
-##References
733
-
734
-
735
-https://sites.google.com/a/wellesley.edu/wellesley-cs118-spring13/lectures-labs/lab-2
1
+## [\[English\]](README-en.md) - for README in English
2
+## [\[Spanish\]](README-es.md) - for README in Spanish