Documentos de Académico
Documentos de Profesional
Documentos de Cultura
C++ Clase 1
C++ Clase 1
MIS PRIMEROS
CDIGOS
EN C++
V4.0
SEPTIEMBRE 2009
FERREIRAS.
Ferreiras
DE INTERS PREVIO
La universidad no presta lo que la
naturaleza no da
Por el dinero del trabajo los dioses
lo venden todo
http://www.zator.com/Cpp/E1_4.htm
Ferreiras
Ferreiras
LA APRECIACIN DE LAS
TCNICAS DE DISEO Y
PROGRAMACIN ES MUCHO MAS
IMPORTANTE QUE EL TOTAL
ENTENDIMIENTO DE LOS DETALLES;
ESE ENTENDIMIENTO VIENE CON LA
PRACTICA Y EL TIEMPO.
Ferreiras
QU ES CONSTRUIR UNA
APLICACIN C++ ?
CONSTRUIR UNA APLICACIN
C++ ES TRANSFORMAR EL
ALGORITMO DE LA SOLUCIN DE
UN PROBLEMA EN UN
PROGRAMA EJECUTABLE;
Ferreiras
LO INDICADO ANTERIORMENTE
IMPLICA QUE YA USTED CUMPLE
CON EL PRERREQUISITO DE
SABER PASAR DEL PROBLEMA A LA
ESCRITURA DEL ALGORITMO DE LA
SOLUCIN EN PSEUDOCODIGO, SI
NO ES AS, VER TEMA 3 DE INF206.-;
Ferreiras
UN PROGRAMA EJECUTABLE ,
LLAMADO TAMBIN APLICACIN,
ES, SIMPLEMENTE, UN PROGRAMA
EN CDIGO DE UNA MQUINA
ESPECFICA (CPU) QUE PUEDE
SER EJECUTADO POR UN SISTEMA
OPERATIVO;
Ferreiras
Ferreiras
HERRAMIENTAS BSICAS
USADAS PARA CONSTRUIR
APLICACIONES C++
1) El compilador ( bcc32 5.5 / 5.6);
2) El enlazador ( ilink32.exe);
3) El bibliotecario (tlib.exe);
Ferreiras
10
El compilador, el enlazador y el
bibliotecario son herramientas de lnea de
comando, esto significa que son diseada
para ser corridas desde la consola DOS
(cmd.exe), el bash de unix-linux u otras
similares;
Ferreiras
11
.cpp
archivo
fuente
Ferreiras
.obj
compilador
(bcc32)
MIS PRIMEROS CODIGO
S C++
archivo
objeto
12
.obj
archivo
objeto
.exe
enlazador
archivo
ejecutable
(ilink32)
Ferreiras
13
DESCOMPILAR UN
EJECUTABLE C++ ?
NO SUEEN, NO HAY
FORMA DE USTED
OBTENER EL CDIGO
FUENTE C++ A PARTIR DE
UN EJECUTABLE CREADO
CON UN O UNOS ARCHIVOS
OBJETOS C++;
Ferreiras
14
.obj
.obj
.obj
.lib
.obj
.obj
Ferreiras
.obj
bibliotecario
(tlib)
librera
esttica
15
El compilador incluye
opciones de lnea de comando
que invocan la accin propia del
compilador ( !compilar!) y el
enlazador, entre otras;
Ferreiras
16
17
Para compilar el
archivo fuente .cpp y
generar el archivo
objeto .obj
18
C:\Borland\BCC55\Bin>bcc32
Todas las
opciones
podemos
verlas si
hacemos:
Ferreiras
Borland C++ 5.5 for Win32 Copyright (c) 1993, 2000 Borland
Syntax is: BCC32 [ options ] file[s] * = default; -x- = turn switch x off
-3 * 80386 Instructions
-4
80486 Instructions
-5
Pentium Instructions
-6
Pentium Pro Instructions
-Ax Disable extensions
-B
Compile via assembly
-C
Allow nested comments -Dxxx Define macro
-Exxx Alternate Assembler name -Hxxx Use pre-compiled headers
-Ixxx Include files directory -K
Default char is unsigned
-Lxxx Libraries directory
-M
Generate link map
-N
Check stack overflow
-Ox Optimizations
-P
Force C++ compile
-R
Produce browser info
-RT * Generate RTTI
-S
Produce assembly output
-Txxx Set assembler option
-Uxxx Undefine macro
-Vx Virtual table control -X
Suppress autodep. output
-aN Align on N bytes
-b * Treat enums as integers
-c
Compile only
-d
Merge duplicate strings
-exxx Executable file name
-fxx Floating point options
-gN Stop after N warnings -iN Max. identifier length
-jN Stop after N errors
-k * Standard stack frame
-lx Set linker option
-nxxx Output file directory
-oxxx Object file name
-p
Pascal calls
-tWxxx Create Windows app
-u * Underscores on externs
-v
Source level debugging -wxxx Warning control
-xxxx Exception handling
-y
Produce line number info
-zxxx Set segment names
19
EL COMPILADOR A USAR
Nombre ?
Borland C++ 5.5 Command Line
Dnde obtenerlo ?
http://www.programacionenc.net/modules.php?name=Tutoriales&d_op=vertuto&lid=25
Cmo instalarlo ?
En el mismo link esta la explicacin.
En el CD entregado por el Prof. esta todo.
Ferreiras
20
POR QU LNEA DE
COMANDO?
POR ASPECTOS DIDCTICOS. EN
ESTA PARTE ESTAMOS
CONSTRUYENDO CONCEPTOS
ESENCIALES QUE SERN LA
INFRAESTRUCTURA DE LOS
CONOCIMIENTOS DE NUESTRO
PRODUCTO FINAL, UN PROFESIONAL
DE LA TIC.
Ferreiras
21
22
d) Un linker;
b) Compilador;
c) Depurador;
f) ...
Ferreiras
23
24
Ferreiras
25
Ferreiras
26
Ferreiras
27
Ferreiras
28
COMPILADOR C++
MULTIPLATAFORMA ?
CADA PLATAFORMA ( CPU + SO)
TIENE SU PROPIO CPU, EL CUAL
TIENE SU PROPIO LENGUAJE
(CONJUNTO DE INSTRUCCIONES) AL
QUE RESPONDE;
Ferreiras
29
Ferreiras
30
LUEGO, COMPILE Y
ENLACE EN CADA
PLATAFORMA CON EL
COMPILADOR Y EL
ENLAZADOR APROPIADO. ES
TODO LO QUE SE REQUIERE.
Ferreiras
31
Ferreiras
32
PASOS REQUERIDOS1
PARA CONSTRUIR UNA
APLICACIN CON C++
1) CDIGO FUENTE
Son las instrucciones de C++ que
componen el programa. Se escribe con un
editor de texto ASCII-std, como notepad,
notepad++, edit, vi, ..., respetando las
reglas del lenguaje;
1
Ferreiras
33
C:\Borland\BCC55\bin>
Ferreiras
34
C:\Borland\BCC55\bin>
bcc32 c nombre.cpp <ENTER>
Ferreiras
35
Ferreiras
36
Ferreiras
37
4) ENLAZAR (link)
Para producir un programa que se pueda
correr ( ejecutable) en el computador hay
que enlazar el o los archivos nombre.obj :
C:\Borland\BCC55\bin>
bcc32 l nombre.obj <ENTER>
El ejecutable generado se llamar
nombre.exe
Ferreiras
38
Ferreiras
39
C:\Borland\BCC55\bin>
nombre <ENTER>
PUEDE ESTAR EN CUALQUIER DIRECTORIO Y ES IGUAL:
nombre <ENTER>
Ferreiras
40
LA EJECUCIN INDICADA ES EN
LNEA DE COMANDO Y HEMOS
SUPUESTO QUE NO REQUIERE DE
ARGUMENTOS ADICIONALES LA
INSTRUCCIN DE EJECUCIN; MS
ADELANTE EXPLICAREMOS Y
VEREMOS LA EJECUCIN CON
ARGUMENTOS EN LNEA DE
COMANDO.
Ferreiras
41
PRODUCCIN DE UNA
APLICACIN C++
EL
PROBLEMA
SUGERENCIA: Repasar las PPTs
INF206_Tema_03 de INF-206.
Todas estn en el grupo.
Ferreiras
42
ANLISIS
Y
DOMINIO
DEL
PROBLEMA
Ferreiras
43
DECLARACIN
DEL
PROBLEMA
(NARRATIVA)
Ferreiras
44
ENFOQUE E-P-S
E
ENTRADA
P
PROCESO
S
SALIDA
45
DISEO
DEL
ALGORITMO
Ferreiras
46
ESCRIBIR
EL
ALGORITMO
EN
PSEUDOCODIGO
Ferreiras
47
ESCRIBIR EL
PSEUDOCODIGO
DEL
ALGORITMO
EN CDIGO
FUENTE C++
Ferreiras
48
EN NOTEPAD:
ESCRBALO AS ENTRE
PAR DE COMILLAS
DOBLES
1) NOMBRE: bas1.cpp
2) Tipo: Documento de texto (*.txt)
3) Codificacin: ANSI
Ferreiras
49
COMPILAR EL
CDIGO
FUENTE
Ferreiras
50
Ferreiras
51
Ferreiras
52
Ferreiras
53
Ferreiras
54
55
PROBAMOS LA APLICACIN,
CORRIENDO EL ARCHIVO .exe :
<ENTER>
Ferreiras
56
Ferreiras
57
58
CICLO C - G - C:
C: CORRECCIN
G: GRABACIN
SALIR DE
ESTE CICLO
CUANDO YA
NO HAY
ERRORES DE
SINTAXIS
C: COMPILACIN
Ferreiras
59
EN RESUMEN
EDITOR
ASCII
DECLARACIN DEL
PROBLEMA
ALGORITMO
COMPILACION
>bcc32 c a.cpp
a.cpp
ENLAZADO
SI
ERRORES ?
NO
a.obj
>bcc32 -l a.obj
a.exe
60
61
ESTRUCTURA GENERAL
DE UN PROGRAMA FUENTE C++
// DIRECTIVAS DE PREPROCESAMIENTO
#include <iostream>
#include <conio>
#include <math>
// ESPACIO DE NOMBRE ESTANDAR
using namespace std;
// DECLARACIONES GLOBALES
// DEFINICIONES DE FUNCIONES
Ferreiras
62
// FUNCION PRINCIPAL
int main(void){
// cuerpo de main
return 0;
}
Ferreiras
63
64
65
OPERACIONES DE
ENTRADA / SALIDA
En C++ podemos hacer operaciones de
entrada (LEER) y salida (ESCRIBIR) desde y
hacia:
1) Dispositivos estndar de E/S (Teclado /
Pantalla);
2) Archivos en dispositivos de almacenamiento
masivo y permanente (Discos, ...);
3) Cadenas de caracteres;
Ferreiras
66
programa
Ferreiras
programa
SALIDA
67
SENTENCIA DE SALIDA
Permiten a nuestro algoritmo mostrar el
resultado del procesamiento de los datos.
ALGORITM
O
Ferreiras
RESULTADOS
68
SENTENCIA DE ENTRADA
Permiten a nuestro algoritmo interactuar
con el exterior capturando los datos a ser
procesados.
DATOS A
PROCESAR
Ferreiras
ALGORITMO
69
DISPOSITIVO
DE ENTRADA
bytebytebytebytebytbytebyttebyte
PROGRAMA
DISPOSITIVO
DE SALIDA
bytebytebytebytebytbytebyttebyte
Ferreiras
70
ES
T
BY
E
OD
J
U
FL
DE
IA N
C
N NE S
E
R IO T E
E
F AC BY
S
N RM DE
A
TR NFO MA
I
R
O
F
Ferreiras
71
Ferreiras
72
Ferreiras
73
Ferreiras
74
Ferreiras
75
INSERCIN, PONER Y
ALMACENAR SON SINNIMOS
CUANDO SE HABLA DE SALIDA DE
BYTES HACIA UN CONSUMIDOR
(DISPOSITIVO DE SALIDA);
Ferreiras
76
77
TECLADO
PANTALLA
# 1 stdout
p
r
o
g
r
a
m
a
canales
TERMINAL DE TEXTO
Ferreiras
78
79
Ferreiras
80
81
82
cout <<
cout <<
expresin;
83
endl
cout <<
84
SALIDA
<<
cout
byte1byte2byte3byte
OPERADOR
DE INSERCIN
EN EL FLUJO
ESTNDAR DE
SALIDA
# 1 stdout
DE RAM AL MONITOR
Ferreiras
85
# include <iostream>
using namespace std;
int main(void){
cout << endl << endl << "!! Aqui estamos !! "
<< endl << endl << "En C++ con Ferreiras"
<< endl << endl << "Tema: C++ Basico"
<< "\n\n VAMOS A TRABAJAR 24/7 !!";
cout << endl << endl;
return 0;
}
Ferreiras
86
/*
int64bits
Compilador: bcc32 5.5
C++ / Ferreiras / Tipos fundamentales de datos en C++
Tipo __int64
__int64 support both signed and unsigned data type. If it is signed
then it can hold (2^63) - 1 at max. For unsigned it can hold
(2^64) - 1:
* signed [ -( 2^(64-1) ), ( +(2^(64-1))-1 ) ]
-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
* unsigned [ 0, (+(2^64)- 1) ]
18446744073709551615 [ Er diablo, cuantos numeros !! ]
*/
Ferreiras
87
#include <iostream>
using namespace std;
int main(void){
unsigned __int64 entero_grande(18446744073709551615);
cout << endl << entero_grande << endl;
return 0;
}
/*
C:\Borland\BCC55\Bin>int64bits
18446744073709551615
*/
Ferreiras
88
!! Aqui estamos !!
En C++ con Ferreiras
Tema: C++ Basico
VAMOS A TRABAJAR 24/7 !!
Ferreiras
89
cin >>
cin >> variable;
La ejecucin del programa se detiene a esperar una entrada
suplida por el teclado ignorando los whispaces que sean pulsados
antes (barra espaciadora, tecla enter, tab);
En esta variable es que se captura la informacin, por lo tanto,
el tipo debe ser correspondiente con el tipo de dato a capturar.
Al terminar la captura (extraccin) cin agrega un newline en
el flujo estndar de entrada;
La extraccin es hasta el primer espacio en blanco;
Ferreiras
90
ENTRADA
# 0 stdin
cin
byte1byte2byte3byte
Ferreiras
>>
OPERADOR DE
EXTRACCIN DEL FLUJO
ESTNDAR DE ENTRADA
91
/*
bas1a.cpp
Compilador: bcc32 5.5
C++/ Ferreiras/ Flujos estandar de E-S /
uso de cout << y de cin >>
*/
Ferreiras
92
# include <iostream>
# include <string>
using namespace std;
int main(void){
string nombre, apellido, completo;
cout << "\n\nENTRADA Y SALIDA ESTANDAR EN C++";
cout << "\n\nENTRE SU NOMBRE [UNA SOLA PALABRA]: ";
cin >> nombre;
cout << "\nENTRE SU APELLIDO [UNA SOLA PALABRA]: ";
cin >> apellido;
cout << "\n\n VERIFICACION DE LA CAPTURA";
cout << "\n\n NOMBRE: " << nombre;
cout << "\n\nAPELLIDO: " << apellido << endl;
Ferreiras
93
Ferreiras
94
C:\Borland\BCC55\Bin>bas1a
ENTRADA Y SALIDA ESTANDAR EN C++
ENTRE SU NOMBRE [UNA SOLA PALABRA]: Fresdebindo
ENTRE SU APELLIDO [UNA SOLA PALABRA]: Leupocito
VERIFICACION DE LA CAPTURA
NOMBRE: Fresdebindo
APELLIDO: Leupocito
AREA T como 1/2*b*h = 0
AREA T como 1.0/2.0*b*h = 1.4391
Ferreiras
95
Los dos primeros cout son ejecutados completamente antes de que cin se
ejecute; Por igual, el cin se ejecuta completamente antes del siguiente
cout. ;
Ferreiras
96
LECTURA SIMULTANEA
EN MAS DE UNA VARIABLE
//...
string nombre; long matricula; double pago;
// En vez de hacer esto:
cin >> nombre;
cin >> matricula;
cin >> pago;
// C++ permite combinar en un solo cin la
// captura simultanea de las tres variables:
cin >> nombre >> matricula >> pago;
//...
Ferreiras
97
USO DE
getline(cin, str, [delim] )
getline(cin, str, [delim]);
nos permite capturar un flujo de
entrada estndar incluyendo los
espacios en blanco;
[...] Significa opcional.
Ferreiras
98
Ferreiras
99
Ferreiras
100
/*
bas1b.cpp
Compilador: bcc32 5.5
C++/ Ferreiras/ Flujos estandar de E-S /
uso de getline( cin, str, [delim] )
*/
Ferreiras
101
# include <iostream>
# include <string>
using namespace std;
int main(void){
string completo;
cout << "\n\nENTRADA Y SALIDA ESTANDAR EN C++" << endl;
cout << "\nENTRE SU NOMBRE Y APELLIDO COMPLETOS:\n ";
getline(cin, completo);
cout << "\n\n VERIFICACION DE LA CAPTURA" << endl;
cout << "\nCOMPLETO: " << completo << endl;
return 0;
}
Ferreiras
102
/*
C:\Borland\BCC55\Bin>bas1b
ENTRADA Y SALIDA ESTANDAR EN C++
ENTRE SU NOMBRE Y APELLIDO COMPLETOS:
Fresdebindo Leupocito Colgadero Sanchez
VERIFICACION DE LA CAPTURA
COMPLETO: Fresdebindo Leupocito Colgadero Sanchez
*/
Ferreiras
103
USO COMBINADO DE
getline y cin
En el uso combinado de getline y
cin hay que tener en cuenta que si
usamos primero el cin, entonces
getline pasar como una voladora de
FENATRANO y no leer nada. Ver en el
ejemplo bas4.cpp la solucin de eso.
Ferreiras
104
<sstream>
PROVEE LOS RECURSOS PARA
OPERACIONES DE E/S BASADAS EN
CADENAS:
ESCRIBIR HACIA UNA CADENA;
LEER DESDE UNA CADENA.
A VER MS ADELANTE.
Ferreiras
105
<fstream>
PROPORCIONA RECURSOS PARA LA
EJECUCIN DE OPERACIONES DE
FLUJOS E/S SOBRE ARCHIVOS EN
DISCOS.
A SER DISCUTIDO EN OTRO TEMA
Ferreiras
106
GRACIAS !!
Ferreiras
107