sábado, 29 de março de 2008

MS VS 2005 C++ :: Uso de array de ponteiros para objetos de uma classe

 

Conforme apresentada inicialmente a solução do projeto "Estatísticas" em MS VS 2005 C++, alguns tropeços aconteceram quanto ao uso de array de ponteiros para objetos de uma classe.

Pesquisando um pouco mais, o link abaixo mostra alguma luz para esse problema:

http://msdn.microsoft.com/vstudio/tour/vs2005_guided_tour/VS2005pro/Framework/CPlusLanguageFeatures.htm

 

No projeto, as modificações foram feitas nos seguintes trechos:

 

1) Declaração do array de objetos gerenciáveis da classe "Estatisticas":

#pragma once

#include <stdio.h>

#include "Estatisticas.h"

namespace oop1a {

    // A declaração a seguir foi substituída por outra logo mais abaixo nos atributos da classe Form1

    //Estatisticas *detalhada[27];          

    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;
    using namespace System::Runtime::InteropServices;

    /// <summary>
    /// Summary for Form1
    ///
    /// WARNING: If you change the name of this class, you will need to change the
    ///          'Resource File Name' property for the managed resource compiler tool
    ///          associated with all .resx files this class depends on.  Otherwise,
    ///          the designers will not be able to interact properly with localized
    ///          resources associated with this form.
    /// </summary>


    public ref class Form1 : public System::Windows::Forms::Form
    {
    private:

        // Declaração de ponteiro para objeto gerenciável pelo DOT-NET FRAMEWORK

        Estatisticas   ^geral;

        FILE *fh;
        int uf, qtd;
        bool abrir;

        // Outra maneira de declarar um array de ponteiros para objetos de uma classe
        // Declaração de um array de ponteiros para objetos gerenciáveis da classe Estatisticas
        // Atenção: ver modificação da classe no arquivo "Estatisticas.h"

        array<Estatisticas^>    ^detalhada;

    public:
        Form1(void)
        {
            InitializeComponent();
            //
            //TODO: Add the constructor code here
            //
        }

    protected:
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        ~Form1()
        {
            if (components)
            {
                delete components;
            }
        }

 

2) Instanciando e destruindo os objetos gerenciáveis:

private: System::Void button3_Click(System::Object^  sender, System::EventArgs^  e) {

                  // botão Estatística Detalhada

                 int i;

                 if ( abrir == false ) return;
                 // converter string em char e abrir o arquivo

                 System::String ^ filename = openFileDialog1->FileName ;

                 char* filenameANSI = (char*)(void*)Marshal::StringToHGlobalAnsi(filename);

                 fh = fopen( filenameANSI, "r" );

                 Marshal::FreeHGlobal( (IntPtr)filenameANSI );

                 // Instanciar um array de 27 elementos do tipo Estatisticas^
                 // Estatisticas^ necessita ser uma classe para objetos gerenciáveis
                 // Usa-se "gcnew" no lugar de "new" para objetos gerenciáveis
                 // Define-se "gcnew" como "garbage collector new"
                 // Nenhum objeto do array é instanciado nesta etapa
                 // Atenção: ver modificação da classe no arquivo "Estatisticas.h"

                 detalhada = gcnew array<Estatisticas^>(27);

                 // instanciamento de cada objeto do array através do "gcnew"

                 for (i = 0; i < 27; i++)
                 {
                         detalhada[i] = gcnew Estatisticas();
                 }

                 while ( true ){

                        fscanf(fh, "%d %d", &uf, &qtd);

                        if ( uf == 0 ) break;

                        detalhada[ uf - 1 ]->Acumular( qtd );
                 }

                 geral->Calcular();

                 listBox1->Items->Clear();

                 for (i = 0; i < 27; i++){

                        detalhada[i]->Calcular();

                        listBox1->Items->Add( "Média[" +
                                      System::Convert::ToString(i + 1) + "]: " +
                                      System::Convert::ToString( detalhada[i]->media ) );

                 }

                 fclose( fh );

                 // destruir o array de objetos gerenciáveis

                 delete[]   detalhada;

         }

 

3) Modificação necessária na declaração da interface da classe "Estatisticas":

// Estatisticas.h

// É requerido declarar a classe como "ref" para trabalhar com objetos gerenciáveis pelo dot-net

ref   class   Estatisticas {

    public: int cnt;
    public: int somatoria;
    public: int media;

    Estatisticas( );         // Construtor

    public: void Acumular( int );
    public: void Calcular( );

    ~Estatisticas( );        // Destrutor

};

 

4) Resumindo, desta maneira os conceitos de OOP trabalhados e aplicados em projetos desenvolvidos no MS VS 2005 C++:

array<Estatisticas^>    ^detalhada;                     // declaração

detalhada = gcnew array<Estatisticas^>(27);     // instanciamento do array

for (i = 0; i < 27; i++)
{
       this->detalhada[i] = gcnew Estatisticas();    // instanciar objeto [i]
                                                                               //
individualmente
}

delete[] detalhada;                                                // destruição

Agora, no CBuilder para fazer o mesmo:

Estatistica    *detalhada[27];                                // declaração

for (i = 0; i < 27; i++){
       detalhada[i] = new Estatistica();                   // instanciar objeto [i]
                                                                               // individualmente
}

delete [] detalhada;                                              // destruição

 

Até mais.

sábado, 8 de março de 2008

Mãos à obra :: Praticando OOP com CBuilder e MS VS 2005 C++

Tempo dedicado à prática.

Bom trabalho.

Lógica2 :: Projeto "Estatísticas" feito em MS Visual Studio 2005 C++

 

O projeto segue a mesma linha como feito no CBuilder. A primeira imagem anexada é da interface gráfica.

image

A segunda, já em execução do "openFileDialog".

image

A terceira, quando solicitada a estatística geral.

image

E a última imagem a seguir, da estatística detalhada.

image

A seguir temos o código para a aplicação desenvolvida em MS VS 2005 C++:

1) Arquivo "Formulario.h"

#pragma once

#include <stdio.h>

#include "Estatisticas.h"

namespace oop1a {

    // O array de ponteiros para objetos da classe Estatistica não pode ser definida como atributo
    // de classe, como feito no CBuilder:

    Estatisticas *detalhada[27];

    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;

    // namespace necessária ao uso de Marshal para converter string em char:

    using namespace System::Runtime::InteropServices;

    /// <summary>
    /// Summary for Form1
    ///
    /// WARNING: If you change the name of this class, you will need to change the
    ///          'Resource File Name' property for the managed resource compiler tool
    ///          associated with all .resx files this class depends on.  Otherwise,
    ///          the designers will not be able to interact properly with localized
    ///          resources associated with this form.
    /// </summary>
    public ref class Form1 : public System::Windows::Forms::Form
    {
    private:

        Estatisticas *geral;
        FILE *fh;
        int uf, qtd;
        bool abrir;

    public:
        Form1(void)
        {
            InitializeComponent();
            //
            //TODO: Add the constructor code here
            //
        }

    protected:
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        ~Form1()
        {
            if (components)
            {
                delete components;
            }
        }
    private: System::Windows::Forms::Button^  button1;
    private: System::Windows::Forms::Button^  button2;
    private: System::Windows::Forms::Button^  button3;
    private: System::Windows::Forms::ListBox^  listBox1;
    private: System::Windows::Forms::OpenFileDialog^  openFileDialog1;
    protected:

    private:
        /// <summary>
        /// Required designer variable.
        /// </summary>
        System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        void InitializeComponent(void)
        {
            this->button1 = (gcnew System::Windows::Forms::Button());
            this->button2 = (gcnew System::Windows::Forms::Button());
            this->listBox1 = (gcnew System::Windows::Forms::ListBox());
            this->openFileDialog1 = (gcnew System::Windows::Forms::OpenFileDialog());
            this->button3 = (gcnew System::Windows::Forms::Button());
            this->SuspendLayout();
            //
            // button1
            //
            this->button1->Location = System::Drawing::Point(12, 69);
            this->button1->Name = L"button1";
            this->button1->Size = System::Drawing::Size(154, 23);
            this->button1->TabIndex = 0;
            this->button1->Text = L"Sai&r";
            this->button1->UseVisualStyleBackColor = true;
            this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
            //
            // button2
            //
            this->button2->Location = System::Drawing::Point(12, 12);
            this->button2->Name = L"button2";
            this->button2->Size = System::Drawing::Size(154, 23);
            this->button2->TabIndex = 1;
            this->button2->Text = L"Estatística Geral";
            this->button2->UseVisualStyleBackColor = true;
            this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click);
            //
            // listBox1
            //
            this->listBox1->FormattingEnabled = true;
            this->listBox1->Location = System::Drawing::Point(209, 12);
            this->listBox1->Name = L"listBox1";
            this->listBox1->Size = System::Drawing::Size(337, 264);
            this->listBox1->TabIndex = 2;
            //
            // button3
            //
            this->button3->Location = System::Drawing::Point(12, 41);
            this->button3->Name = L"button3";
            this->button3->Size = System::Drawing::Size(154, 23);
            this->button3->TabIndex = 3;
            this->button3->Text = L"Estatítica Detalhada";
            this->button3->UseVisualStyleBackColor = true;
            this->button3->Click += gcnew System::EventHandler(this, &Form1::button3_Click);
            //
            // Form1
            //
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(626, 357);
            this->Controls->Add(this->button3);
            this->Controls->Add(this->listBox1);
            this->Controls->Add(this->button2);
            this->Controls->Add(this->button1);
            this->Name = L"Form1";
            this->Text = L"Estatísticas";
            this->FormClosed += gcnew System::Windows::Forms::FormClosedEventHandler(this, &Form1::Form1_FormClosed);
            this->Shown += gcnew System::EventHandler(this, &Form1::Form1_Shown);
            this->ResumeLayout(false);

        }
#pragma endregion

    private: System::Void Form1_Shown(System::Object^  sender, System::EventArgs^  e) {

                 // quando da exibição do form pela primeira vez

                 openFileDialog1->Title      = "Abrir Dados";
                 openFileDialog1->Filter     = "Parâmetros (*.txt)|*.txt";
                 openFileDialog1->DefaultExt = "txt";

                 if ( openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK ){
                     abrir = true;
                 }
                 else{
                     abrir = false;
                 }
         }

    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {

                 // botão Sair

                 Application::Exit();
             }

    private: System::Void Form1_FormClosed(System::Object^  sender, System::Windows::Forms::FormClosedEventArgs^  e) {

                 // form Close

                 Application::Exit();
             }

    private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) {

                 // botão Estatística Geral

                 if ( abrir == false ) return;

                 // converter string em char e abrir o arquivo

                 System::String ^ filename = openFileDialog1->FileName ;

                 char* filenameANSI = (char*)(void*)Marshal::StringToHGlobalAnsi(filename);

                 fh = fopen( filenameANSI, "r" );

                 Marshal::FreeHGlobal( (IntPtr)filenameANSI );

                 geral = new Estatisticas();      // instanciar objeto

                 while ( true ){

                        fscanf(fh, "%d %d", &uf, &qtd);

                        if ( uf == 0 ) break;

                        geral->Acumular( qtd );
                 }

                 geral->Calcular();

                 listBox1->Items->Clear();

                 listBox1->Items->Add( "Média Geral: " +
                                       
System::Convert::ToString ( geral->media ) );

                 fclose( fh );

                 delete geral;           // destruir objeto

             }

private: System::Void button3_Click(System::Object^  sender, System::EventArgs^  e) {

                  // botão Estatística Detalhada

                 int i;

                 if ( abrir == false ) return;
              
 
                 // converter string em char e abrir o arquivo

                 System::String ^ filename = openFileDialog1->FileName ;

                 char* filenameANSI = (char*)(void*)Marshal::StringToHGlobalAnsi(filename);

                 fh = fopen( filenameANSI, "r" );

                 Marshal::FreeHGlobal( (IntPtr)filenameANSI );

                 for (i = 0; i < 27; i++){
                        detalhada[i] = new Estatisticas(); // instanciar objeto[i]
                 }

                 while ( true ){

                        fscanf(fh, "%d %d", &uf, &qtd);

                        if ( uf == 0 ) break;

                        detalhada[ uf - 1 ]->Acumular( qtd );
                 }

                 geral->Calcular();

                 listBox1->Items->Clear();

                 for (i = 0; i < 27; i++){

                        detalhada[i]->Calcular();

                        listBox1->Items->Add( "Média[" +
                                      System::Convert::ToString(i + 1) + "]: " +
                                      System::Convert::ToString( detalhada[i]->media ) );

                 }

                 fclose( fh );

          // a destruição dos objetos precisou ser individualmente:

                 for (i = 0; i < 27; i++){
                    delete detalhada[i];           // destruir objeto[i]
                 }

         }
};
}

2) Arquivo "Estatistica.h"

// Estatisticas.h

class Estatisticas {

    public: int cnt;
    public: int somatoria;
    public: int media;

    Estatisticas( );         // Construtor

    public: void Acumular( int );
    public: void Calcular( );

    ~Estatisticas( );        // Destrutor

};

3) Arquivo "Estatistica.cpp"

#include "stdafx.h"

#include "Estatisticas.h"

Estatisticas :: Estatisticas( )            // Construtor
{
    cnt = 0;
    somatoria = 0;
    media = 0;
}

void Estatisticas :: Acumular( int a )
{
    cnt ++;
    somatoria += a;
    return;
}

void Estatisticas :: Calcular( )
{
    if ( cnt > 0){
        media = somatoria / cnt;
    }
    return;
}

Estatisticas :: ~Estatisticas( )        // Destrutor
{
}

4) Arquivo "Dados.txt"

1 2000
2 4000
3 3500
4 3600
5 1200
3 500
2 800
2 3800
4 1250
5 540
1 6500
3 420
1 8700
3 9500
2 1240
1 370
5 850
3 1230
2 3290
1 4320
0 0

Usando MS Visual Studio 2005 C++

Procedimentos para conversão de strings de "System::String" para "char*"

Situação em que dados de uma interface gráfica ( textBox1->Text ) necessitam ser gravados em arquivos texto ANSI através da biblioteca "stdio".

1) declarar uso da biblioteca "stdio"

        #include <stdio.h>

2) declarar uso do nome de espaço "InteropServices":

        using namespace System::Runtime::InteropServices;

3) código para converter "System::String" em "char*":

        System::String ^ str = textBox1->Text ;
        char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(str);

        FILE *fh = fopen( "teste.txt", "w" );
        fprintf(fh, "%s", str2);
        fclose(fh);

        Marshal::FreeHGlobal((IntPtr)str2);

Adaptado da Fonte de Referência:

http://support.microsoft.com/kb/311259

Lógica2 :: Projeto "Estatísticas" feito no CBuilder

 

Abaixo temos a interface com: 3 botões, 1 listbox e 1 opendialog:

image

Na ativação do form, a aplicação irá requisitar a identificação do arquivo a ser processado:

image

Após isso, fica a critério do usuário pedir estatística geral ou detalhada:

image

image

A seguir o código para a classe TForm1:

1) Aplicativo.h

//---------------------------------------------------------------------------

#ifndef AplicativoH
#define AplicativoH
//-------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <Dialogs.hpp>

#include <stdio.h>
#include "Estatistica.h"

//-------------------------------------------------------------------------
class TForm1 : public TForm
{
__published:    // IDE-managed Components
        TButton *Button1;
        TListBox *ListBox1;
        TButton *Button2;
        TOpenDialog *OpenDialog1;
        TButton *Button3;
        void __fastcall Button2Click(TObject *Sender);
        void __fastcall FormClose(TObject *Sender, TCloseAction &Action);
        void __fastcall Button1Click(TObject *Sender);
        void __fastcall Button3Click(TObject *Sender);
        void __fastcall FormActivate(TObject *Sender);


private:    // User declarations

        FILE *fh;
        Estatistica *geral, *detalhada[27];
        int uf, qtd;
        bool abrir;

public:        // User declarations
        __fastcall TForm1(TComponent* Owner);

};

//-------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//-------------------------------------------------------------------------
#endif

 

2) Aplicativo.cpp

//-------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Aplicativo.h"

//-------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//-------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//-------------------------------------------------------------------------
void __fastcall TForm1::FormActivate(TObject *Sender)
{
        OpenDialog1->Title      = "Abrir Dados";
        OpenDialog1->Filter     = "Parâmetros (*.txt)|*.txt";
        OpenDialog1->DefaultExt = "txt";

        if ( OpenDialog1->Execute() == false ){
                abrir = false;
        }
        else{
                abrir = true;
        }
}
//-------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
        // botão Sair

        Application->Terminate() ;
}
//-------------------------------------------------------------------------
void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
{
        // fechar form

        Application->Terminate() ;
}
//-------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
        // botão Estatística Geral

        if ( abrir == false ) return;

        fh = fopen(OpenDialog1->FileName.c_str(), "r");

        geral = new Estatistica();      // instanciar objeto

        while ( true ){

                fscanf(fh, "%d %d", &uf, &qtd);

                if ( uf == 0 ) break;

                geral->Acumular( qtd );
        }

        geral->Calcular();

        ListBox1->Items->Clear();
        ListBox1->Items->Add( "Média Geral: " + String( geral->media ) );

        fclose( fh );

        delete geral;           // destruir objeto
}
//-------------------------------------------------------------------------
void __fastcall TForm1::Button3Click(TObject *Sender)
{
        // botão Estatística Detalhada

        int i;

        if ( abrir == false ) return;

        fh = fopen(OpenDialog1->FileName.c_str(), "r");

        if ( fh == NULL ) return;

        for (i = 0; i < 27; i++){
                detalhada[i] = new Estatistica(); // instanciar objeto[i]
        }

        while ( true ){

                fscanf(fh, "%d %d", &uf, &qtd);

                if ( uf == 0 ) break;

                detalhada[ uf - 1 ]->Acumular( qtd );
        }

        ListBox1->Items->Clear();

        for (i = 0; i < 27; i++){

                detalhada[i]->Calcular();

                ListBox1->Items->Add( "Média[" +
                                     
String(i + 1) + "]: " +
                                      String( detalhada[i]->media ) );

        }
        fclose( fh );

        delete [] detalhada;           // destruir array de objetos
}
//-------------------------------------------------------------------------

 

Agora temos o código para a classe Estatistica:

1) Estatistica.h

//-------------------------------------------------------------------------

#ifndef EstatisticaH
#define EstatisticaH

class Estatistica{

        private: int cont;
        private: int soma;
        public: int media;

        Estatistica();          // construtor

        public: void Acumular( int );
        public: void Calcular();

        ~Estatistica();         // destrutor

};

//-------------------------------------------------------------------------
#endif

 

2) Estatistica.cpp

//-------------------------------------------------------------------------

#pragma hdrstop

#include "Estatistica.h"

//-------------------------------------------------------------------------

#pragma package(smart_init)

Estatistica :: Estatistica(){   // construtor
        cont = 0;
        soma = 0;
        media = 0;
        return;
}

void Estatistica :: Acumular( int q ){
        cont ++;
        soma += q;
        return;
}

void Estatistica :: Calcular() {
        if ( cont > 0 ){
                media = soma / cont;
        }
        return;
}

Estatistica :: ~Estatistica(){  // destrutor
        return;
}

//-------------------------------------------------------------------------

 

Por último, aqui estão os dados utilizados nos testes:

1 2000
2 4000
3 3500
4 3600
5 1200
3 500
2 800
2 3800
4 1250
5 540
1 6500
3 420
1 8700
3 9500
2 1240
1 370
5 850
3 1230
2 3290
1 4320
0 0

 

Lógica2 - Primeiro Projeto OOP em C++

 

Projeto desenvolvido na aula de sexta-feira 22/02/2008.

 

Foi testado com o compilador GCC no ambiente Linux e com o Borland C Compiler v.5.5 em ambiente Windows XP.

 

Download do BCC32 free: http://www.codegear.com/downloads/free/cppbuilder

 

Notar alguns detalhes no código:

1) ao declarar a "visibilidade" do atributo/método, usar ":" como no exemplo:

private: int atributo;

public: float Metodo( int, int, int );

 

2) usando a notação '->' para referir-se a um atributo/método desse objeto, é requerido declará-lo com alocação dinâmica de memória, através de ponteiros, como no exemplo:

Veiculo *meriva;            // declaração

Veiculo *civic;             // declaração

meriva = new Veiculo( );    // instanciamento

civic = new Veiculo( );     // instanciamento

meriva->cor = 1;            // fixar valor em atributo do objeto

civic->cor = 2;             // fixar valor em atributo do objeto

delete meriva;              // destruição do objeto

delete civic;               // destruição do objeto

 

3) para usar a outra  forma de referir-se a um atributo/método com a notação ".", é necessário declará-lo com alocação estática de memória:

Veiculo meriva = Veiculo( );     // declaração e instanciamento

Veiculo civic = Veiculo( );     // declaração e instanciamento

meriva.cor = 1;            // fixar valor em atributo do objeto

civic.cor = 2;             // fixar valor em atributo do objeto

/* Observar: não requer o comando "delete", já que a alocação é estática, e sendo assim, somente quando o escopo do código encerrar é que serão liberados os recursos de memória para objetos estáticos; */

 

A seguir, códigos em C++ para:

Aplicativo.cpp

Estatisticas.h

Estatisticas.cpp

 

//---------<Aplicativo.cpp>----------------------------------------------

// Aplicativo.cpp

/*

    CEFET-SP :: TADS :: LG2

    Prof. Josimar Nunes de Oliveira - 2008

    0) Ambiente (GNU/Linux :: Fedora 7):

        # c++ -v
        Using built-in specs.
        Target: x86_64-redhat-linux
        Configured with: ../configure
                --prefix=/usr
                --mandir=/usr/share/man
                --infodir=/usr/share/info
                --enable-shared
                --enable-threads=posix
                --enable-checking=release
                --with-system-zlib
                --enable-__cxa_atexit
                --disable-libunwind-exceptions
                --enable-languages=c,c++,objc,obj-c++,java,fortran,ada
                --enable-java-awt=gtk
                --disable-dssi
                --enable-plugin
                --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-1.5.0.0/jre
                --enable-libgcj-multifile
                --enable-java-maintainer-mode
                --with-ecj-jar=/usr/share/java/eclipse-ecj.jar
                --with-cpu=generic
                --host=x86_64-redhat-linux
        Thread model: posix
        gcc version 4.1.2 20070925 (Red Hat 4.1.2-27)

    1) Arquivos fontes:

        Aplicativo.cpp
        Estatisticas.h
        Estatiscas.cpp

    2) Compilação & Linkagem:

        # c++ Aplicativo.cpp Estaticas.cpp -o Apl

    3) Arquivo binário executável:

        ./Apl

    4) Arquivo de dados:

        Dados.txt

    5) Execução do programa binário:

        # ./Apl < Dados.txt

       Observação: o programa utiliza os métodos 'std::cin' e 'std::cout' que acessam respectivamente a entrada e a saída padrão do sistema; logo, usando o redirecionador da entrada padrão '<', os dados serão lidos do arquivo, facilitando os testes.


    6) Ambiente MS Windows XP/SP2:

        Compilador:     BORLAND C COMPILER 5.5

        Comando:        bcc32 Aplicativo.cpp Estatisticas.cpp

        Executável:     Aplicativo.exe

        Teste:          Aplicativo < Dados.txt

*/

#include "Estatisticas.h"

#include <iostream>

using std::cin;
using std::cout;

// declaração global de objetos:

Estatisticas *ba;

int main( )
{
    // declaração local de variáveis:

    int uf, valor;
    bool fim_arq = false;

    // declaração local de objetos:

    Estatisticas *sp;
    Estatisticas *rj;
    Estatisticas *mg;
    Estatisticas *es;

    // instanciamento de objetos:

    sp = new Estatisticas( );
    rj = new Estatisticas( );
    mg = new Estatisticas( );
    es = new Estatisticas( );

    while ( ! fim_arq )
    {
        // Ler dados da entrada padrão (teclado):

        cin >> uf;
        cin >> valor;

        // Executar método 'Acumular( int )' para o respectivo objeto:

        switch ( uf )
        {
            case 1:               
                sp->Acumular( valor );        // SP
                break;
            case 2:       
                rj->Acumular( valor );        // RJ
                break;
            case 3:       
                mg->Acumular( valor );        // MG
                break;
            case 4:       
                es->Acumular( valor );        // ES
                break;
            case 0:       
                fim_arq = true;            // fim de arquivo
                break;
        }
    }

    // Executar método 'Medias()' de cada objeto:

    sp->Medias( );   
    rj->Medias( );   
    mg->Medias( );   
    es->Medias( );
   

    // Imprimir atributo 'media' de cada objeto:

    cout << "\n\n";

    cout << "\nSP: " << sp->media;
    cout << "\nRJ: " << rj->media;
    cout << "\nMG: " <<
mg->media;
    cout << "\nES: " << es->media;

    cout << "\n\n";

    // Destruir objetos:

    delete sp;
    delete rj;
    delete mg;
    delete es;

    // fim do aplicativo:

    return 0;

}

//---------</Aplicativo.cpp>---------------------------------------------

 

//---------<Estatisticas.h>----------------------------------------------

// Estatisticas.h

class Estatisticas {

    public: int cnt;
    public: int somatoria;
    public: int media;

    Estatisticas( );         // Construtor

    public: void Acumular( int );
    public: void Medias( );

    ~Estatisticas( );        // Destrutor

};

//---------</Estatisticas.h>---------------------------------------------

 

//---------<Estatisticas.cpp>--------------------------------------------

// Estatisticas.cpp

#include "Estatisticas.h"

Estatisticas :: Estatisticas( )            // Construtor
{
    cnt = 0;
    somatoria = 0;
    media = 0;
}

void Estatisticas :: Acumular( int a )
{
    cnt ++;
    somatoria += a;
    return;
}

void Estatisticas :: Medias( )
{
    media = somatoria / cnt;
    return;
}

Estatisticas :: ~Estatisticas( )        // Destrutor
{
}

//---------</Estatisticas.cpp>-------------------------------------------

 

//---------<Dados.txt>---------------------------------------------------

1 2000
2 4000
3 3500
4 3600
5 1200
3 500
2 800
2 3800
4 1250
5 540
1 6500
3 420
1 8700
3 9500
2 1240
1 370
5 850
3 1230
2 3290
1 4320
0 0

//---------</Dados.txt>--------------------------------------------------

 

//---------<Resultado_Linux>---------------------------------------------

[root@localhost projetos_lg2]# ./Apl < Dados.txt

SP: 4378
RJ: 2626
MG: 3030
ES: 2425

[root@localhost projetos_lg2]#

//---------</Resultado_Linux>--------------------------------------------

 

//---------<Resultado_Windows_XP>----------------------------------------

C:\projetos_lg2>Aplicativo.exe < Dados.txt

SP: 4378
RJ: 2626
MG: 3030
ES: 2425

C:\projetos_lg2>

//---------</Resultado_Windows_XP>---------------------------------------

 

Sexta-feira 15/02/2008 - Lógica2

 

Como era de se esperar, poucos apareceram para aula inicial de Lógica2.

Aguardando o pessoal chegar, iniciamos uma discussão sobre virtualização, processadores, linguagens de programação e dot net framework da microsoft.

Após esse quebra-gelo, trabalhamos uma introdução aos conceitos que norteiam a programação orientada a objetos (OOP) e que certamente será reapresentada na próxima sexta-feira.

Para quem não foi, discutimos as idéias básicas que alicerçam a OOP:

  • conceito de classes;
  • exercício da abstração de algo a ser concretizado: características (atributos) e funcionalidades (métodos);
  • criação de um objeto como sendo a concretização de um elemento de uma classe;
  • os recursos que um objeto consome durante sua existência: espaço (memória) e tempo (processamento);
  • controle do ciclo de vida de um objeto: iniciar (instanciamento) e finalizar (destruição);
  • identidade de objetos: ocorrências de objetos de uma mesma classe possuem mesmas características e funcionalidades, mas não são uma mesma entidade, pois cada ocorrência tem uma identidade própria, única e natural que os distingüe uns dos outros;
  • comunicação com os objetos: a interação com os objetos é feita com mensagens que solicitam a execução de uma funcionalidade, passando e retornando dados;

Paramos aqui e retomaremos novamente estes conceitos na próxima aula.

Até lá.

Adaptando-se ao novo espaço.

Vendo como funciona.

sexta-feira, 7 de março de 2008