linguagem de programação i -...

Post on 25-Dec-2018

218 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

LinguagemdeProgramaçãoI

CarlosEduardoBa6sta

CentrodeInformá6ca-UFPBbidu@ci.ufpb.br

C++ePOO

•  Mo6vaçãoparaousodeC++paraoaprendizadodePOO

•  QuandousarCequandousarC++•  C++versusJava•  SintaxebásicadeC++•  AmbientesdedesenvolvimentoC++

2

Mo6vaçãoparaousodeC++

3

Mo6vaçãoparaousodeC++

•  Aprendizadoincremental(apar6rdeC)•  Controlederecursosedesempenho– Gerênciadememória“manual”– AbstraçõesPOO+Responsabilidade

•  Maiorcontroledacompilação•  AprenderC++facilitaoaprendizadoposteriordeJava

•  Maisfácildeseo6mizarodesempenho•  C++nãoélinguagemparapreguiçosos

4

QuandousarCequandousarC++•  C–  Códigodebaixonível(drivers,kernel)– Disposi6vosembarcados(suporte)–  Fortesrequisitosdedesempenho*

•  C++–  Sistemasdeinfraestrutura–  90%dosjogossãoemC++–  Sistemasoperacionais(Windows,*nix)

•  OndeC/C++nãosãopopulares...– Disposi6vosmóveis(iOSeAndroid)– Web

5

C++versusJava

•  Padronização– C++•  ISO/IEC14882•  ISO/IECJTC1/SC22/WG21commikee•  C++11

–  Java•  JavaLanguageSpecifica6on(Oracle)

6

C++versusJava•  C++–  EstendeC(linguagemimpera6va/procedural)–  AcrescentasuporteaPOOde6pagemestá6ca

•  Tratamentodeexceções•  Gerenciamentodeescopo•  Metaprogramação(templates)•  Bibliotecapadrão(STD)•  Writeonce,compileanywhere(WOCA)

•  Java•  SintaxefortementebaseadaemC/C++•  Máquinavirtual(JVM)•  Concorrência•  JNI–JavaNa6veInterface•  Writeonce,runanywhere(WORA)

7

C++versusJava

•  AssimilamalgunsconceitosdePOOdeformadiferente

•  hkp://en.wikipedia.org/wiki/Comparison_of_Java_and_C++

8

SintaxebásicadeC++

•  HelloWorld•  Declarações•  I/O•  DeStructsemCaClassesemC++

9

SintaxebásicadeC++

10

#include <iostream> // incluir biblioteca de IO int main() // função onde o programa é iniciado { cout << "Hello World"; // exibe "Hello World" return 0; // devolve ao SO. o valor 0 (sucesso)}

SintaxebásicadeC++

•  Declarações– EmANSICasdeclaraçõesantecedemasinstruções

– EmC99eC++asdeclaraçõeseinstruçõespodemsemisturar

– Declaraçõesnacondiçãodeumainstruçãodo6poif•  Servecomoumarestriçãodeescopo(oblocodefinidopeloif)

11

SintaxebásicadeC++

12

double g(int a, double d){ return a * d;}void f(double p){ int i = 0; double result;

//... if (p <= 10.0) i++; //...

result = g(i,p); }

int main(){ f(5.0);}

SintaxebásicadeC++

13

double g(int a, double d){ return a * d;}void f(double p){ int i = 0;

// ... if (p <= 10.0) i++; // ...

double result = g(i,p); //Declara e usa result }

int main(){ f(5.0);}

SintaxebásicadeC++

•  Declaraçãodentrodeif– Atribuiçãodeveiniciarcondição

•  Declaraçãoemoutrasinstruções/laços

14

// se get() retorna valor diferente de NULL// realiza instrução w->fire()if(weapon *w = get()) { w->fire();}

if(int i = value) ...;for(...; int i = value; ...) ...;switch(int i = value) ...;while(int i = value) ...;

SintaxebásicadeC++

•  EntradaeSaídaemC++– <ostream>e<istream>

•  Operadores– >>(pegarde)– <<(porem)

•  prinxescanf– Nãosãogeneralizáveispara6posdefinidospelousuário

15

SintaxebásicadeC++

•  cin–entradapadrão•  cout–saídapadrão•  cerr–saídadeerropadrão•  Estados–  stream.good()–  stream.eof()–  stream.fail()–  stream.bad()

16

SintaxebásicadeC++

17

#include <iostream>#include <string>

using namespace std;

int main(){ int i;

while (cin >> i) // boolean - conversão implícita cout << 2*i << " ";

cout << "The End";

}

SintaxebásicadeC++•  Manipuladores

–  AceitospelosoperadoresdeE/S<<e>>–  Alteraoestadodostream–  Ponteiroparaumafunção

18

#include <iostream>#include <iomanip>#include <string>

using namespace std;

int main(){

cout << 17 << endl << showbase << hex << 17 << endl << oct << 17 << endl; }

//17//0x11//021

SintaxebásicadeC++

19

#include <iostream>#include <iomanip>#include <string>

using namespace std;

int main(){ double d = 3.12345678;

cout << d << endl << scientific << d << endl << fixed << setprecision(10) << setfill('#')

<< setw(18) << d << endl;}

//3.12346//3.123457e+00//######3.1234567800

SintaxebásicadeC++

•  Deestruturasaclasses...•  Definirumaestruturagenéricaquedepoispodeteralgumasdesuaspartesmodificadas

•  Hierarquia“6pode”•  Ponteirosparafunções•  AntesdenosaprofundarmosnosconceitosdoparadigmaOO...

20

SintaxebásicadeC++

•  Definindoclasses/objetosemC++•  Umobjetoéumainstânciadeumaclasseereferenciaalgo(delimitado)namemória

•  DeclarandoclassesemC++•  Atributos•  Funçõesmembro(métodos)

21

SintaxebásicadeC++

22

class Casa{public: int numero, numQuartos;

bool jardim;};

main(){

Casa minhaCasa;minhaCasa.numero=500; minhaCasa.numQuartos=4;minhaCasa.jardim=1;return 0;

}

SintaxebásicadeC++

23

class Retangulo{public:

int altura, largura;int area(){

return altura*largura;}

};main(){

Retangulo r;r.altura=5;r.largura=2;cout << r.area();return 0;

}

SintaxebásicadeC++

24

class Retangulo{public:

int altura, largura;int area();

};int Retangulo::area()

{return altura*largura;

}

main(){

Retangulo r;r.altura=5;r.largura=2;cout << r.area();return 0;

}

SintaxebásicadeC++

•  Construtoreseinicializaçãodevariáveisdeumobjeto– Variáveisnecessáriasparaarealizaçãodefuncionalidadesoferecidaspeloobjeto

•  Paracadamembro(instância)umainicializaçãodis6nta

25

SintaxebásicadeC++

26

class Retangulo{private:

int altura, largura;public:

Retangulo(int a, int l) {altura=a;largura=l;

}int area() {

return altura*largura;}

};main() {

Retangulo r(5, 2);cout << r.area();return 0;

}

git

•  Sistemadecontroledeversõesdearquivos•  Comumenteusadocomoferramentaparacontroledeversõesdeartefatodeso/ware

•  CriadoporLinusTorvaldsem2005•  Velocidade,integridade,suporteaworkflowsnãolineares

27

CVSeSVN

git

git

•  Snapshotsenãodeltas•  “Naturalmente”Distribuído– commaioriadasoperaçõesfeitaslocalmente

•  Garan6adeintegridade

git

•  3estadosdoarquivo– Consolidado(commited)– Modificado(modified)– Preparado(staged)

git

git

•  seusrepositórioslocaisconsistememtrês"árvores"man6daspelogit.aprimeiradelasésuaWorkingDirectoryquecontémosarquivosvigentes.

•  asegundaIndexquefuncionacomoumaáreatemporária

•  finalmenteaHEADqueapontaparaoúl6mocommit(confirmação)quevocêfez.

33

git

•  OworkflowbásicodoGitpodeserdescritoassim:– Vocêmodificaarquivosnoseudiretóriodetrabalho.

– Vocêselecionaosarquivos,adicionandosnapshotsdelesparasuaáreadepreparação.

– Vocêfazumcommit,quelevaosarquivoscomoelesestãonasuaáreadepreparaçãoeosarmazenapermanentementenoseudiretórioGit.

git•  arquivo/etc/gitconfig:Contémvaloresparatodosusuários

dosistemaetodososseusrepositórios.Sevocêpassaraopção--systemparagitconfig,eleleráeescreveráapar6rdestearquivoespecificamente.

•  arquivo~/.gitconfig:Éespecíficoparaseuusuário.VocêpodefazeroGitlereescreverapar6rdestearquivoespecificamentepassandoaopção--global.

•  arquivodeconfiguraçãonodiretóriogit(ouseja,.git/config)dequalquerrepositórioquevocêestáu6lizandonomomento:Específicoparaaqueleúnicorepositório.Cadanívelsobrepõemovalordonívelanterior,sendoassimvaloresem.git/configsobrepõemaquelesem/etc/gitconfig.

git

•  $gitconfig--globaluser.name"JohnDoe"•  $gitconfig--globaluser.emailjohndoe@example.com

git•  $gitinit•  $gitclonegit://github.com/schacon/grit.git

•  gitpull

•  $gitadd*.c•  $gitaddREADME•  $gitcommit-m'ini6alprojectversion’•  $gitpushoriginmaster

git

•  gitremoteaddorigin<URL_PARA_SERVIDOR>

•  gitcheckout–bNOME_NOVO_BRANCH•  gitcheckoutmaster•  gitpushorigin<NOME_BRANCH>•  gitbranch–dNOME

38

git

•  gitdiff<arquivo>

•  gitcheckout<arquivo>

39

git

Autotools

•  Sistemadebuild•  Instalaçãoeconfiguração•  Instalaçãodedadoseprogramasseparadamente

•  Cross-compiling•  Rastreamentodedependências•  Aninhamentodebuilds

•  Ferramentasparacriarumsistemadebuildportável,completoeauto-con6do(compa�velcomGNU)

•  $./configure;make;makeinstall•  configure.aceMakefile.am

Helloworld!/* hello.c: A standard "Hello, world!" program */ #include <stdio.h> int main(int argc, char* argv[]){ printf("Hello, world!\n"); return 0;}

#Makefile:AstandardMakefileforhello.call:helloclean:rm-fhello*.o

HelloWorld

$ lsMakefile hello.c$ makecc hello.c -o hello$ lsMakefile hello* hello.c$ ./hello Hello, world!$

HelloWorld

•  Autoconf•  configure.ac(configure.innasversõesan6gas)– Criadousandooautoscan

$ autoscan$ lsMakefile autoscan.log configure.scan hello* hello.c$ mv configure.scan configure.ac$

HelloWorld

$ autoconf$ lsMakefile autoscan.log configure.ac hello.cautom4te.cache/ configure* hello*$

$ mv Makefile Makefile.in$ lsMakefile.in autoscan.log configure.ac hello.cautom4te.cache/ configure* hello*$

Referências

•  hkp://www.cplusplus.com/doc/tutorial/•  hkp://gillius.org/ooptut/•  hkp://people.cs.aau.dk/~normark/ap/basic-facili6es.html

•  hkp://linuxgazeke.net/issue55/williams.html•  https://git-scm.com

47

Próximasaula

•  FundamentaçãodeOrientaçãoaObjetos(OO).

•  SistemasorientadaaobjetosusandoC++

48

LinguagemdeProgramaçãoI

CarlosEduardoBa6sta

CentrodeInformá6ca-UFPBbidu@ci.ufpb.br

top related