-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathV2-Intro.xml
1079 lines (1002 loc) · 49.6 KB
/
V2-Intro.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="utf-8"?>
<!-- -*- sgml -*- -->
<!--
Editor: Emacs 22/PSGML
Traducción original: Javier Peris
Formateado DocBook:
-->
<!-- original en:
http://arco.inf-cr.uclm.es/~david.villa/pensar_en_C++/TICv2/html/TicV2.html#_Toc53985615
-->
<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.3//EN"
"http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd">
<chapter
xmlns:xi="http://www.w3.org/2001/XInclude"
id="Intro">
<!-- Introduction -->
<title>Introducción</title>
<!--
In Volume 1 of this book, you learned the fundamentals of C and
C++. In this volume, we look at more advanced features, with an eye
towards developing techniques and ideas that produce robust C++
programs.
-->
<para>
En el volumen 1 de este libro, aprendió los fundamentos de C y
C++. En este volumen, veremos características más avanzadas, con
miras hacia técnicas e ideas para realizar programas robustos en
C++.
</para>
<!-- We assume you are familiar with the material presented in Volume 1. -->
<para>
Asumimos que está familiarizado con el material presentado en el
Volumen 1.
</para>
<sect1>
<!-- Goals -->
<title>Objetivos</title>
<!-- Our goals in this book are to: -->
<para>
Nuestros objetivos en este libros son:
</para>
<!--
1. Present the material a simple step at a time, so the reader
can easily digest each concept before moving on.
-->
<para>
1. Presentar el material como un sencillo paso cada vez, de este
modo el lector puede asimilar cada concepto antes de seguir
adelante.
</para>
<!--
2. Teach "practical programming" techniques that you can use on a
day-to-day basis.
-->
<para>
2. Enseñar técnicas de "programación práctica" que puede usar en
la base del día a día.
</para>
<!--
3. Give you what we think is important for you to understand about the
language, rather than everything we know. We believe there is an
"information importance hierarchy", and there are some facts that 95%
of programmers will never need to know, but that would just confuse
people and add to their perception of the complexity of the
language. To take an example from C, if you memorize the operator
precedence table (we never did) you can write clever code. But if you
must think about it, it will confuse the reader/maintainer of that
code. So forget about precedence and use parentheses when things
aren't clear. This same attitude will be taken with some information
in the C++ language, which is more important for compiler writers than
for programmers.
-->
<para>
3. Darle lo que pensamos que es importante para que entienda el
lenguaje, más bien que todo lo que sabemos. Creemos que hay una
"jerarquía de importancia de la información", y hay algunos hechos
que el 95% de los programadores nunca necesitarán conocer, sino
que sólo confundiría a la gente y añade complejidad a su
percepción del lenguaje. Tomando un ejemplo de C, si
memoriza la tabla de prioridad de operadores (nosotros nunca lo
hicimos) puede escribir código ingenioso. Pero si debe
pensarlo, confundirá al lector/mantenedor de ese código. De modo
que olvide las precedencias y use paréntesis cuando las cosas no
estén claras.
</para>
<!--
4. Keep each section focused enough so the lecture time-and the time
between exercise periods-is small. Not only does this keep the
audience' minds more active and involved during a hands-on seminar,
but it gives the reader a greater sense of accomplishment.
-->
<para>
4. Manténgase suficientemente centrado en cada sección de modo que el
tiempo de lectura -y el tiempo entre ejercicios- sea
pequeño. Esto no sólo hace mantener las mentes de los lectores
más activas e involucradas durante un seminario práctico sino
que da al lector un mayor sentido de éxito.
</para>
<!--
5. We have endeavored not to use any particular vendor's version of
C++. We have tested the code on all the implementations we could
(described later in this introduction), and when one implementation
absolutely refused to work because it doesn't conform to the C++
Standard, we've flagged that fact in the example (you'll see the
flags in the source code) to exclude it from the build process.
-->
<para>
Hemos procurado no usar ninguna versión de un vendedor
particular de C++. Hemos probado el código sobre todas las
implementaciones que pudimos (descriptas posteriormente en esta
introducción), y cuando una implementación no funciona en
absoluto porque no cumple el Estándar C++, lo hemos señalado en
el ejemplo(verá las marcas en el código fuente) para excluirlo
del proceso de construcción.
</para>
<!--
6. Automate the compiling and testing of the code in the book. We have
discovered that code that isn't compiled and tested is probably
broken, so in this volume we've instrumented the examples with test
code. In addition, the code that you can download from
http://www.MindView.net has been extracted directly from the text of
the book using programs that automatically create makefiles to compile
and run the tests. This way we know that the code in the book is
correct.
-->
<para>
6. Automatizar la compilación y las pruebas del código en el
libro. Hemos descubierto que el código que no está compilado y
probado probablemente no funcione correctamente, de este modo en
este volumen hemos provisto a los ejemplos con código de
pruebas. Además, el código que puede descargar desde
http://www.MindView.net ha sido extraído directamente del texto
del libro usando programas que automáticamente crean makefiles
para compilar y ejecutar las pruebas. De esta forma sabemos que
el código en el libro es correcto.
</para>
</sect1>
<sect1>
<!-- Chapters -->
<title>Capítulos</title>
<!-- Here is a brief description of the chapters contained in this book: -->
<para>
Aquí está una breve descripción de los capítulos que contiene
este libro:
</para>
<!-- Part 1: Building Stable Systems -->
<para>
Parte 1: Construcción de sistemas estables
</para>
<!--
1. Exception handling. Error handling has always been a problem in
programming. Even if you dutifully return error information or set a
flag, the function caller may simply ignore it. Exception handling is
a primary feature in C++ that solves this problem by allowing you to
"throw" an object out of your function when a critical error
happens. You throw different types of objects for different errors,
and the function caller "catches" these objects in separate error
handling routines. If you throw an exception, it cannot be ignored, so
you can guarantee that something will happen in response to your
error. The decision to use exceptions affects code design in positive,
fundamental ways.
-->
<para>
1. Manejar excepciones. Manejar errores ha sido siempre un problema
en programación. Incluso si obedientemente devuelve información
del error o pone una bandera, la función que llama puede
simplemente ignorarlo. Manejar excepciones es una cualidad
primordial en C++ que soluciona este problema permitiéndole
"lanzar" un objeto fuera de su función cuando ocurre un error
crítico. Tire diferentes tipos de objetos para diferentes
errores, y la función que llama "coge" estos objetos en rutinas
separadas de gestión de errores. Si lanza una excepción, no puede
ser ignorada, de modo que puede garantizar que algo ocurrirá en
respuesta a su error. La decisión de usar excepciones afecta
al diseño del código positivamente, de modo fundamental.
</para>
<!--
2. Defensive Programming. Many software problems can be prevented. To
program defensively is to craft code in such a way that bugs are found
and fixed early before they can damage in the field. Using assertions
is the single most important way to validate your code during
development, while at the same time leaving an executable
documentation trail in your code that reveals your thoughts while you
wrote the code in the first place. Rigorously test your code before
you let out of your hands. An automated unit testing framework is an
indispensable tool for successful, everyday software development.
-->
<para>
2. Programación defensiva. Muchos problemas de software pueden ser
prevenidos. Programar de forma defensiva es realizar cuidadosamente
código de tal modo que los bugs son encontrados y arreglados
pronto antes que puedan dañar en el campo. Usar aserciones es
la única y más importante forma para validar su código durante el
desarrollo, dejando al mismo tiempo seguimiento ejecutable de la
documentación en su código que muestra sus pensamientos mientras
escribe el código en primer lugar. Pruebe rigurosamente su
código antes de darlo a otros. Un marco de trabajo de pruebas
unitario automatizado es una herramienta indispensable para el
éxito, en el desarrollo diario de software.
</para>
<!-- Part 2: The Standard C++ Library -->
<para>
Parte 2: La biblioteca estándar de C++
</para>
<!--
3. Strings in Depth. The most common programming activity is text
processing. The C++ string class relieves the programmer from memory
management issues, while at the same time delivering a powerhouse of
text processing capability. C++ also supports the use of wide
characters and locales for internationalized applications.
-->
<para>
3. Cadenas en profundidad. La actividad más común de programación
es el procesamiento de texto. La clase string de C++ libera al
programador de los temas de gestión de memoria, mientras al
mismo tiempo proporciona una fuente de recursos para el
procesamiento de texto. C++ también facilita el uso de una gran
variedad de caracteres y locales para las aplicaciones de
internacionalización.
</para>
<!--
4. Iostreams. One of the original C++ libraries-the one that provides
the essential I/O facility-is called iostreams. Iostreams is intended
to replace C's stdio.h with an I/O library that is easier to use,
more flexible, and extensible-you can adapt it to work with your new
classes. This chapter teaches you how to make the best use of the
existing iostream library for standard I/O, file I/O, and in-memory
formatting.
-->
<para>
4. Iostreams. Una de las bibliotecas original de C++-la que
proporciona la facilidad básica de I/O-es llamada
iostreams. Iostreams está destinado a reemplazar stdio.h de C
con una biblioteca I/O que es más fácil de usar, más flexible, y
extensible- que puede adaptarla para trabajar con sus nuevas
clases. Este capítulo le enseña cómo hacer el mejor uso de la
biblioteca actual I/O, fichero I/O, y formateo en memoria.
</para>
<!--
5. Templates in Depth. The distinguishing feature of "modern C++" is
the broad power of templates. Templates do more than just create
generic containers. They support development of robust, generic,
high-performance libraries. There is a lot to know about
templates-they constitute, as it were, a sub-language within the C++
language, and give the programmer an impressive degree of control over
the compilation process. It is not an overstatement to say that
templates have revolutionized C++ programming.
-->
<para>
5. Plantillas en profundidad. La distintiva cualidad del "C++
moderno" es el extenso poder de las plantillas. Las plantillas
hacen algo más que sólo crear contenedores genéricos. Sostienen
el desarrollo de bibliotecas robustas, genéricas y de alto
rendimiento.Hay mucho por saber sobre plantillas-constituyen,
como fue, un sub-lenguaje dentro del lenguaje C++, y da al
programador un grado impresionante de control sobre el proceso
de compilación. No es una exageración decir que las plantillas
han revolucionado la programación de C++.
</para>
<!--
6. Generic Algorithms. Algorithms are at the core of computing, and
C++, through its template facility, supports an impressive entourage
of powerful, efficient, and easy-to-use generic algorithms. The
standard algorithms are also customizable through function
objects. This chapter looks at every algorithm in the
library. (Chapters 6 and 7 cover that portion of the Standard C++
library commonly known as the Standard Template Library, or STL.)
-->
<para>
6. Algoritmos genéricos. Los algoritmos son el corazón de la
informática, y C++, por medio de la facilidad de las plantillas,
facilita un impresionante entorno de poder, eficiencia, y
facilidad de uso de algoritmos genéricos. Los algoritmos
estándar son también personalizables a través de objetos de
función. Este capítulo examina cada algoritmo de la
biblioteca. (Capítulos 6 y 7 abarcan esa parte de la biblioteca
Estándar de C++ comúnmente conocida como Biblioteca de Plantilla
Estándar, o STL.)
</para>
<!--
7. Generic Containers & Iterators. C++ supports all the common data
structures in a type-safe manner. You never need to worry about what
such a container holds. The homogeneity of its objects is
guaranteed. Separating the traversing of a container from the
container itself, another accomplishment of templates, is made
possible through iterators. This ingenious arrangement allows a
flexible application of algorithms to containers using the simplest of
designs.
-->
<para>
7. Contenedores genéricos e Iteradores. C++ proporciona todas las
estructuras comunes de datos de modo de tipado fuerte. Nunca
necesita preocuparse sobre qué tiene tal contenedor. La
homogenidad de sus objetos está garantizada. Separar la #FIXME
traversing de un contenedor del propio contenedor, otra
realización de plantillas, se hace posible por medio de los
iteradores. Este ingenioso arreglo permite una aplicación
flexible de algoritmos a contenedores usando el más sencillo de
los diseños.
</para>
<!-- Part 3: Special Topics -->
<para>
Parte 3: Temas especiales
</para>
<!--
8. Runtime type identification. Runtime type identification (RTTI)
finds the exact type of an object when you only have a pointer or
reference to the base type. Normally, you'll want to intentionally
ignore the exact type of an object and let the virtual function
mechanism implement the correct behavior for that type. But
occasionally (like when writing software tools such as debuggers) it
is helpful to know the exact type of an object-with this information,
you can often perform a special-case operation more efficiently. This
chapter explains what RTTI is for and how to use it.
-->
<para>
8. Identificación de tipo en tiempo de ejecución. La identificación
de tipo en tiempo de ejecución (RTTI) encuentra el tipo exacto
de un objeto cuando sólo tiene un puntero o referencia al tipo
base. Normalmente, tendrá que ignorar a propósito el tipo exacto
de un objeto y permitir al mecanismo de función virtual
implementar el comportamiento correcto para ese tipo. Pero
ocasionalmente (como las herramientas de escritura de
software tales como los depuradores) es útil para conocer el
tipo exacto de un objeto-con su información, puede realizar con
frecuencia una operación en casos especiales de forma más
eficiente. Este capítulo explica para qué es RTTT y como usarlo.
</para>
<!--
9. Multiple inheritance. This sounds simple at first: A new class is
inherited from more than one existing class. However, you can end up
with ambiguities and multiple copies of base-class objects. That
problem is solved with virtual base classes, but the bigger issue
remains: When do you use it? Multiple inheritance is only essential
when you need to manipulate an object through more than one common
base class. This chapter explains the syntax for multiple inheritance
and shows alternative approaches-in particular, how templates solve
one typical problem. Using multiple inheritance to repair a "damaged"
class interface is demonstrated as a valuable use of this feature.
-->
<para>
9. Herencia múltiple. Parece sencillo al principio: Una nueva clase
hereda de más de una clase existente. Sin embargo, puede
terminar con copias ambiguas y múltiples de objetos de la clase
base. Ese problema está resuelto con clases bases virtuales,
pero la mayor cuestión continua: ¿Cuándo usarla? La herencia
múltiple es sólo imprescindible cuando necesite manipular un
objeto por medio de más de un clase base común. Este capítulo
explica la sintaxis para la herencia múltiple y muestra enfoques
alternativos- en particular, como las plantillas solucionan un
problema típico. Usar herencia múltiple para reparar un interfaz
de clase "dañada" demuestra un uso valioso de esta cualidad.
</para>
<!--
10. Design Patterns. The most revolutionary advance in programming
since objects is the introduction of design patterns. A design pattern
is a language-independent codification of a solution to a common
programming problem, expressed in such a way that it can apply to many
contexts. Patterns such as Singleton, Factory Method, and Visitor now
find their way into daily discussions around the keyboard. This
chapter shows how to implement and use some of the more useful design
patterns in C++.
-->
<para>
10. Patrones de diseño. El más revolucionario avance en programación
desde los objetos es la introducción de los patrones de
diseño. Un patrón de diseño es una codificación independiente
del lenguaje de una solución a un problema de programación
común, expresado de tal modo que puede aplicarse a muchos
contextos. Los patrones tales como Singleton, Factory Method, y
Visitor ahora tienen lugar en discusiones diarias
alrededor del teclado. Este capítulo muestra como implementar y
usar algunos de los patrones de diseño más usados en C++.
</para>
<!--
11. Concurrent Programming. People have come to expect responsive user
interfaces that (seem to) process multiple tasks
simultaneously. Modern operating systems allow processes to have
multiple threads that share the process address space. Multithreaded
programming requires a different mindset, however, and comes with its
own set of difficulties. This chapter uses a freely available library
(the ZThread library by Eric Crahen of IBM) to show how to effectively
manage multithreaded applications in C++.
-->
<para>
11. Programación concurrente. La gente ha llegado a esperar
interfaces de usuario sensibles que (parece que) procesan
múltiples tareas simultáneamente. Los sistemas operativos
modernos permiten a los procesos tener múltiples hilos que
comparten el espacio de dirección del proceso. La programación
multihilo requiere una perspectiva diferente, sin embargo, y
viene con su propio conjunto de dificultades. Este capítulo
utiliza un biblioteca disponible gratuitamente (la biblioteca
ZThread por Eric Crahen de IBM) para mostrar como gestionar
eficazmente aplicaciones multihilo en C++.
</para>
</sect1>
<sect1>
<!-- Exercises -->
<title>Ejercicios</title>
<!--
We have discovered that simple exercises are exceptionally useful
during a seminar to complete a student's understanding. You'll find
a set at the end of each chapter.
-->
<para>
Hemos descubierto que los ejercicios sencillos son
excepcionalmente útiles durante un seminario para completar la
comprensión de un estudiante. Encontrará una colección al final de
cada capítulo.
</para>
<!--
These are fairly simple, so they can be finished in a reasonable
amount of time in a classroom situation while the instructor observes,
making sure all the students are absorbing the material. Some
exercises are a bit more challenging to keep advanced students
entertained. They're all designed to be solved in a short time and
are only there to test and polish your knowledge rather than present
major challenges (presumably, you'll find those on your own-or more
likely they'll find you).
-->
<para>
Estos son bastante sencillos, de modo que puedan ser acabados en
una suma de tiempo razonable en una situación de clase mientras
el profesor observa, asegurándose que todos los estudiantes están
absorbiendo el material. Algunos ejercicios son un poco más
exigentes para mantener entretenidos a los estudiantes
avanzados. Están todos diseñados para ser resueltos en un tiempo
corto y sólo están allí para probar y refinar su conocimiento
más bien que presentar retos mayores (presumiblemente, podrá
encontrarlos o más probablemente ellos le encontrarán a usted).
</para>
<sect2>
<!-- Exercise solutions -->
<title>Soluciones de los ejercicios</title>
<!--
Solutions to exercises can be found in the electronic document The C++
Annotated Solution Guide, Volume 2, available for a nominal fee from
http://www.MindView.net.
-->
<para>
Las soluciones a los ejercicios pueden encontrarse en el
documento electrónico La Guía de Soluciones Comentada de C++,
Volumen 2, disponible por una cuota simbólica en
http://www.MindView.net.
</para>
</sect2>
</sect1>
<sect1>
<!-- Source code -->
<title>Código fuente</title>
<!--
The source code for this book is copyrighted freeware, distributed via
the web site http://www.MindView.net. The copyright prevents you from
republishing the code in print media without permission.
-->
<para>
El código fuente para este libro está autorizado como software
gratuito, distribuido por medio del sitio web
http://www.MindView.net. Los derechos de autor le impiden volver
a publicar el código impreso sin permiso.
</para>
<!--
In the starting directory where you unpack the code you will find the
following copyright notice:
-->
<para>
En el directorio inicial donde desempaqueta el código encontrará
el siguiente aviso de derechos de autor:
</para>
<!-- :! :CopyRight.txt -->
<para>
<!-- :! :CopyRight.txt -->
</para>
<!--
You may use the code in your projects and in the classroom as long as
the copyright notice is retained.
-->
<para>
Puede usar el código en sus proyectos y en clase siempre que el
aviso de los derechos de autor se conserve.
</para>
</sect1>
<sect1>
<!-- Compilers -->
<title>Compiladores</title>
<!--
Your compiler may not support all the features discussed in this book,
especially if you don't have the newest version of your
compiler. Implementing a language like C++ is a Herculean task, and
you can expect that the features will appear in pieces rather than all
at once. But if you attempt one of the examples in the book and get a
lot of errors from the compiler, it's not necessarily a bug in the
code or the compiler-it may simply not be implemented in your
particular compiler yet.
-->
<para>
Su compilador podría no soportar todas las cualidades discutidas
en este libro, especialmente si no tiene la versión más
nueva de su compilador. Implementar un lenguaje como C++ es un
tarea Hercúlea, y puede suponer que las cualidades aparecen por
partes en lugar de todas juntas. Pero si intenta uno de los
ejemplos del libro y obtiene muchos errores del compilador, no
es necesariamente un error en el código o en el compilador-puede
que sencillamente no esté implementado todavía en su compilador
concreto.
</para>
<!--
We used a number of compilers to test the code in this book, in an
attempt to ensure that our code conforms to the C++ Standard and will
work with as many compilers as possible. Unfortunately, not all
compilers conform to the C++ Standard, and so we have a way of
excluding certain files from building with those compilers. These
exclusions are reflected in the makefiles automatically created for
the package of code for this book that you can download from
www.MindView.net. You can see the exclusion tags embedded in the
comments at the beginning of each listing, so you will know whether to
expect a particular compiler to work on that code (in a few cases, the
compiler will actually compile the code but the execution behavior is
wrong, and we exclude those as well).
-->
<para>
Empleamos un número de compiladores para probar el código de
este libro, en un intento para asegurar que nuestro código
cumple el Estándar C++ y funcionará con todos los compiladores
posibles. Desafortunadamente, no todos los compiladores cumplen
el Estándar C++, y de este modo tenemos un modo de excluir
ciertos ficheros de la construcción con esos compiladores. Estas
exclusiones se reflejadas automáticamente en los makefiles
creados para el paquete de código para este libro que puede
descargar desde www.MindView.net. Puede ver las etiquetas de
exclusión incrustadas en los comentarios al inicio de cada
listado, de este modo sabrá si exigir a un compilador concreto
que funcione con ese código (en pocos casos, el compilador
realmente compilará el código pero el comportamiento de
ejecución es erróneo, y excluimos esos también).
</para>
<!-- Here are the tags and the compilers that they exclude from the
build: -->
<para>
Aquí están las etiquetas y los compiladores que se excluyen
de la construcción.
</para>
<!--
· {-dmc} Walter Bright's Digital Mars compiler for Windows, freely
downloadable at www.DigitalMars.com. This compiler is very
conformant and so you will see almost none of these tags throughout
the book.
-->
<para>
· {-dmc} El Compilador de Mars Digital de Walter Bright para
Windows, descargable gratuitamente en
www.DigitalMars.com. Este compilador es muy tolerante y así
no verá casi ninguna de estas etiquetas en todo el libro.
</para>
<!--
· {-g++} The free Gnu C++ 3.3.1, which comes pre-installed in most
Linux packages and Macintosh OSX. It is also part of Cygwin for
Windows (see below). It is available for most other platforms from
gcc.gnu.org.
-->
<para>
· {-g++} La versión libre Gnu C++ 3.3.1, que viene preinstalada
en la mayoría de los paquetes Linux y Macintosh OSX. También es
parte de Cygwin para Windows (ver abajo). Está disponible para la
mayoría de las plataformas en gcc.gnu.org.
</para>
<!--
· {-msc} Microsoft Version 7 with Visual C++ .NET (only comes with
Visual Studio .NET; not freely downloadable).
-->
<para>
· {-msc} Microsoft Version 7 con Visual C++ .NET (viene sólo con
Visual Studio .NET; no descargable gratuitamente).
</para>
<!--
· {-bor} Borland C++ Version 6 (not the free download; this one is
more up to date).
-->
<para>
· {-bor} Borland C++ Version 6 (no la versión gratuita; éste
está más actualizado).
</para>
<!--
· {-edg} Edison Design Group (EDG) C++. This is the benchmark compiler
for standards conformance. This tag occurs only because of library
issues, and because we were using a complimentary copy of the EDG
front end with a complimentary library implementation from
Dinkumware, Ltd. No compile errors occurred because of the compiler
alone.
-->
<para>
· {-edg} Edison Design Group (EDG) C++. Este es el compilador de
referencia para la conformidad con los estándares. Esta etiqueta
existe a causa de los temas de biblioteca, y porque estábamos
usando un copia gratis de la interfaz EDG con una implementación de la
biblioteca gratuita de Dinkumware, Ltd. No aparecieron errores de
compilación a causa sólo del compilador.
</para>
<!--
· {-mwcc} Metrowerks Code Warrior for Macintosh OS X. Note that OS X
comes with Gnu C++ pre-installed, as well.
-->
<para>
· {-mwcc} Metrowerks Code Warrior para Macintosh OS X. Fíjese que OS X
viene con Gnu C++ preinstalado, también.
</para>
<!--
If you download and unpack the code package for this book from
www.MindView.net, you'll find the makefiles to build the code for the
above compilers. We used the freely-available GNU-make, which comes
with Linux, Cygwin (a free Unix shell that runs on top of Windows; see
www.Cygwin.com), or can be installed on your platform-see
www.gnu.org/software/make. (Other makes may or may not work with these
files, but are not supported.) Once you install make, if you type make
at the command line you'll get instructions on how to build the book'
s code for the above compilers.
-->
<para>
Si descarga y desempaqueta el paquete de código de este libro de
www.MindView.net, encontrará los makefiles para construir el
código para los compiladores de más arriba. Usabamos GNU-make
disponible gratuitamente, que viene con Linux, Cygwin (una
consola gratis de Unix que corre encima de Windows; ver
www.Cygwin.com), o puede instalar en su plataforma, ver
www.gnu.org/software/make. (Otros makes pueden o no funcionar
con estos ficheros, pero no están soportados.) Una vez que
instale make, si teclea make en la línea de comando obtendrá
instrucciones de cómo construir el código del libro para los
compiladores de más arriba.
</para>
<!--
Note that the placement of these tags on the files in this book
indicates the state of the particular version of the compiler at the
time we tried it. It's possible and likely that the compiler vendor
has improved the compiler since the publication of this book. It's
also possible that while building the book with so many compilers, we
may have misconfigured a particular compiler that would otherwise have
compiled the code correctly. Thus, you should try the code yourself on
your compiler, and also check the code downloaded from
www.MindView.net to see what is current.
-->
<para>
Fíjese que la colocación de estas etiquetas en los ficheros en
este libro indica el estado de la versión concreta del
compilador en el momento que lo probamos. Es posible y
probable que el vendedor del compilador haya mejorado el
compilador desde la publicación de este libro. Es posible
también que mientras que realizamos el libro con tantos compiladores, hayamos
desconfigurado un compilador en concreto que en otro caso habría
compilado el código correctamente. Por consiguiente, debería
probar el código usted mismo con su compilador, y comprobar
también el código descargado de www.MindView.net para ver que
es actual.
</para>
</sect1>
<sect1>
<!-- Language standards -->
<title>Estándares del lenguaje</title>
<!--
Throughout this book, when referring to conformance to the ANSI/ISO C
standard, we will be referring to the 1989 standard, and will
generally just say 'C.' Only if it is necessary to distinguish
between Standard 1989 C and older, pre-Standard versions of C will we
make the distinction. We do not reference C99 in this book.
-->
<para>
A lo largo de este libro, cuando se hace referencia a la
conformidad con el ANSI/ISO C estándar, estaremos haciendo
referencia al estándar de 1989, y de forma general diremos
solamente 'C.'. Sólo si es necesario distinguir entre el
Estándar de C de 1989 y anteriores, versiones pre-Estándares de
C haremos la distinción. No hacemos referencia a c99 en este libro.
</para>
<!--
The ANSI/ISO C++ Committee long ago finished working on the first C++
Standard, commonly known as C++98. We will use the term Standard C++
to refer to this standardized language. If we simply refer to C++,
assume we mean "Standard C++." The C++ Standards Committee continues
to address issues important to the C++ community that will become
C++0x, a future C++ Standard not likely to be available for many
years.
-->
<para>
El Comité de ANSI/ISO C++ hace mucho acabó el trabajo sobre el
primer Estándar C++, comunmente conocido como C++98. Usaremos el
término Standard C++ para referirnos a este lenguaje
normalizado. Si nos referimos sencillamente a C++, asuma que
queremos decir "Standard C++". El Comité de Estándares de C++
continua dirigiendo cuestiones importantes para la comunidad de
C++ que se convertirá en C++0x, un futuro Estándar de C++ que no
estará probablemente disponible durante muchos años.
</para>
</sect1>
<sect1>
<!-- Seminars, CD-ROMs & consulting -->
<title>Seminarios, CD-ROMs y consultoría</title>
<!--
Bruce Eckel's company, MindView, Inc., provides public hands-on
training seminars based on the material in this book, and also for
advanced topics. Selected material from each chapter represents a
lesson, which is followed by a monitored exercise period so each
student receives personal attention. We also provide on-site training,
consulting, mentoring, and design & code walkthroughs. Information and
sign-up forms for upcoming seminars and other contact information is
found at http://www.MindView.net.
-->
<para>
La compañía de Bruce Eckel, MindView, Inc., proporciona
seminarios públicos prácticos de formación basados en el
material de este libro, y también para temas avanzados. El
material seleccionado de cada capítulo representa una lección,
que es sucedida por un periodo de ejercicios guiado de tal modo que
cada estudiante recibe atención personalizada. También
facilitamos formación en el lugar, consultoría, tutoría y
comprobación de diseño y código. La información y los
formularios de inscripción para los seminarios próximos y otra
información de contacto se puede encontrar en http://www.MindView.net.
</para>
</sect1>
<sect1>
<!-- Errors -->
<title>Errores</title>
<!--
No matter how many tricks writers use to detect errors, some always
creep in and these often leap off the page for a fresh reader. If you
discover anything you believe to be an error, please use the feedback
system built into the electronic version of this book, which you will
find at http://www.MindView.net. Your help is appreciated.
-->
<para>
No importa cuantos trucos usen los escritores para detectar
errores, algunos siempre pasan desapercibidos y éstos a menudo
destacan para un nuevo lector. Si descubre algo que cree ser un
error, por favor use el sistema de respuesta incorporado en la
versión electrónica de este libro, que encontrará en
http://www.MindView.net. Su ayuda se valora.
</para>
</sect1>
<sect1>
<!-- About the cover -->
<title>Sobre la portada</title>
<!--
The cover artwork was painted by Larry O'Brien's wife, Tina Jensen
(yes, the Larry O'Brien who was the editor of Software Development
Magazine for so many years). Not only are the pictures beautiful, they
are also excellent suggestions of polymorphism. The idea for using
these images came from Daniel Will-Harris, the cover designer
(www.Will-Harris.com), working with Bruce.
-->
<para>
El arte de la portada fue realizado por la mujer de Larry
O'Brien, Tina Jensen (sí, el Larry O'Brien quien fue el editor
de Software Development Magazine durante muchos años). No
solamente los dibujos son bonitos, son también sugerencias
excelentes de polimorfismo. La idea de usar estas imágenes viene de
Daniel Will-Harris, el diseñador de portadas
(www.Will-Harris.com), trabajando con Bruce.
</para>
</sect1>
<sect1>
<!-- Acknowledgements -->
<title>Agradecimientos</title>
<!--
Volume 2 of this book languished in a half-completed state for a long
time while Bruce got distracted with other things, notably Java,
Design Patterns and especially Python (see www.Python.org). If Chuck
hadn't been willing (foolishly, he has sometimes thought) to finish
the other half and bring things up-to-date, this book almost certainly
wouldn't have happened. There aren't that many people whom Bruce
would have felt comfortable entrusting this book to. Chuck's penchant
for precision, correctness and clear explanation is what has made this
book as good as it is.
-->
<para>
El volumen 2 de este libro se descuidó a mitad de estar acabado
durante mucho tiempo mientras Bruce se distraía con otras
cosas, en particular con Java, Patrones de Diseño y especialmente
con Python (ver www.Python.org). Si Chuck no hubiera estado
dispuesto (tontamente, él reflexiona algunas veces) a acabar la
otra mitad y llevar las cosas al día, este libro casi
seguramente no habría existido. No hay mucha gente a quien Bruce
habría confiado tranquilamente este libro. La
afición de Chuck por la precisión, la corrección y la
explicación clara es lo que ha hecho que este libro sea tan
bueno como es.
</para>
<!--
Jamie King acted as an intern under Chuck's direction during the
completion of this book. He was an essential part of making sure the
book got finished, not only by providing feedback for Chuck, but
especially because of his relentless questioning and picking of every
single possible nit that he didn't completely understand. If your
questions are answered by this book, it's probably because Jamie
asked them first. Jamie also enhanced a number of the sample programs
and created many of the exercises at the end of each chapter. Scott
Baker, another of Chuck's interns funded by MindView, Inc., helped
with the exercises for Chapter 3.
-->
<para>
Jamie King trabajó como persona de prácticas bajo la dirección
de Chuck durante la finalización de este libro. El fue una parte
esencial en asegurarse que el libro se finalizaba, no sólo
proporcionando contestación a Chuck, sino especialmente por
su interrogatorio implacable y siendo puntilloso con cada
elección que él no comprendía por completo. Si sus preguntas son
respondidas por este libro, es probablemente porque Jamie las
preguntó primero. Jamie también mejoró unos cuantos programas de
ejemplo y creó muchos de los ejercicios al final de cada
capítulo. Scott Baker, otro trabajador en prácticas de Chuck
patrocinado por MindView, Inc., ayudó con los ejercicios del
capítulo 3.
</para>
<!--
Eric Crahen of IBM was instrumental in the completion of Chapter 11
(Concurrency). When we were looking for a threads package, we sought
out one that was intuitive and easy to use, while being sufficiently
robust to do the job. With Eric we got that and then some-he was
extremely cooperative and has used our feedback to enhance his
library, while we have benefited from his insights as well.
-->
<para>
Eric Crahen de IBM fue decisivo en la finalización del
capítulo 11 (Concurrencia). Cuando estábamos buscando un paquete
de hilos, buscamos uno que fuese intuitivo y fácil de usar,
mientras fuese suficientemente robusto para hacer el
trabajo. Con Eric conseguimos esto y posteriormente- él estuvo
sumamente cooperativo y ha usado nuestras contestaciones
para mejorar su biblioteca, mientras nosotros también nos hemos
beneficiado de su conocimiento.
</para>
<!--
We are grateful to Pete Becker for being our technical editor. Few
people are as articulate and discriminating as Pete, not to mention as
expert in C++ and software development in general. We also thank Bjorn
Karlsson for his gracious and timely technical assistance as he
reviewed the entire manuscript with short notice.
-->
<para>
Estamos agradecidos a Pete Becker por ser nuestro editor
técnico. Pocas personas son tan elocuentes y exigentes como Pete,
ni mencionar como experto en C++ y desarrollo de software
en general. También dar gracias a Bjorn Karlsson por su cortés y
oportuna asistencia técnica revisando el manuscrito entero con
escaso aviso.
</para>
<!--
Walter Bright made Herculean efforts to make sure that his Digital
Mars C++ compiler would compile the examples in this book. He makes
the compiler available for free downloads at
http://www.DigitalMars.com. Thanks, Walter!
-->
<para>
Walter Bright hizo esfuerzos Hercúleos para asegurarse que su
compilador Digital Mars C++ compilaría los ejemplos de este
libro. Puso disponible el compilador mediante descarga gratuita
en http://www.DigitalMars.com. ¡Gracias, Walter!
</para>
<!--
The ideas and understanding in this book have come from many other
sources, as well: friends like Andrea Provaglio, Dan Saks, Scott
Meyers, Charles Petzold, and Michael Wilk; pioneers of the language
like Bjarne Stroustrup, Andrew Koenig, and Rob Murray; members of the
C++ Standards Committee like Nathan Myers (who was particularly
helpful and generous with his insights), Herb Sutter, PJ Plauger,
Kevlin Henney, David Abrahams, Tom Plum, Reg Charney, Tom Penello, Sam
Druker, Uwe Steinmueller, John Spicer, Steve Adamczyk, and Daveed
Vandevoorde; people who have spoken in the C++ track at the Software
Development Conference (which Bruce created and developed, and Chuck
spoke in); Colleagues of Chuck like Michael Seaver, Huston Franklin,
David Wagstaff, and often students in seminars, who ask the questions
we need to hear to make the material clearer.
-->
<para>
Las ideas y conocimientos de este libro provienen también de
muchas otras fuentes: amigos como Andrea Provaglio, Dan
Saks, Scott Meyers, Charles Petzold, y Michael Wilk; los
pioneros del lenguaje como Bjarne Stroustrup, Andrew Koening,
y Rob Murray; los miembros del Comité de Estándares de C++ como
Nathan Myers (quien fue especialmente servicial y generoso con
sus perspicacias), Herb Sutter, PJ Plauger, Kevlin Henney,
David Abrahams, Tom Plum, Reg Charney, Tom Penello, Sam Druker,
Uwe Steinmueller, John Spicer, Steve Adamczyk, y Daveed
Vandevoorde; la gente que ha hablado en el apartado de C++ de la
Conferencia de Desarrollo de Software (que Bruce creó y
desarrolló, y en la que habló Chuck); Compañeros de Chuck como
Michael Seaver, Huston Franklin, David Wagstaff, y muchos
estudiantes en seminarios, quienes realizaron las preguntas que
necesitamos escuchar para hacer el material más claro.
</para>
<!--
The book design, typeface selection, cover design, and cover photo
were created by Bruce's friend Daniel Will-Harris, noted author and
designer, who used to play with rub-on letters in junior high school
while he awaited the invention of computers and desktop
publishing. However, we produced the camera-ready pages ourselves, so
the typesetting errors are ours. Microsoft® Word XP was used to write
the book and to create camera-ready pages. The body typeface is
Verdana and the headlines are in Verdana. The code type face is
Courier New.
-->
<para>
El diseño del libro, la elección de la fuente, el diseño de la
portada, y la foto de la portada ha sido realizada por el amigo
de Bruce Daniel Will-Harris, célebre autor y desiñador, que
solía jugar con cartas temporales en el primer ciclo de
secundaria mientras esperaba la invención de los ordenadores y
la publicación asistida por ordenador. Sin embargo, presentamos
las páginas listas para imprimir nosotros mismos, por lo tanto
los errores de composición tipográfica son nuestros. Se ha usado
Microsoft® Word XP para escribir el libro y crear la versión
lista para imprimir. El cuerpo del texto está en Verdana y los
títulos está en Verdana. El tipo de letra del código es Courier
New.
</para>
<!--
We also wish to thank the generous professionals at the Edison Design
Group and Dinkumware, Ltd., for giving us complimentary copies of
their compiler and library (respectively). Without their expert
assistance, graciously given, some of the examples in this book could
not have been tested. We also wish to thank Howard Hinnant and the
folks at Metrowerks for a copy of their compiler, and Sandy Smith and
the folks at SlickEdit for keeping Chuck supplied with a world-class
editing environment for so many years. Greg Comeau also provided a
copy of his successful EDG-based compiler, Comeau C++.
-->