1

olá,gostaria de saber como faço para passar um objeto criado em c++ como parametro de uma função de outro objeto,vi no forum em inglês,mas não entendi muito bem como faz,se alguém puder me ajudar,agradeceria

classes que eu estou usando no objeto

dominios.h

#ifndef DOMINIOS_H
#define DOMINIOS_H

#include <string>
#include <sstream>
#include <math.h>
#include <stdexcept>
using namespace std;

class CodProjeto{
    public:
        CodProjeto();
        void Set(string x) throw (invalid_argument);
        string get();
    private:
        string cod;

};

class EstadoProjeto //inserir argumentos invalidos da classe
{
    public:
        EstadoProjeto();
        void Set(int est) throw (invalid_argument);
        int get();
    private:
        int x;

};

class FaseProjeto
{
    public:
        FaseProjeto();
        void Set(int x) throw(invalid_argument);
        int get();
    private:
        int x;
};

class Func
{
    public:
        Func();
        void Set(int x) throw(invalid_argument);
        int get();
    private:
        int x;
};

class data
{
    public:
        data();
        void Set(int d,int m,int a) throw(invalid_argument);
        void Set(string d) throw(invalid_argument);
        int getDia();
        int getMes();
        int getAno();
        string getDATA();
    private:
        int calculadigito(string d,int lim,int pos);
        void verificaformato(string d) throw(invalid_argument);
        int d,m,a;
};

class nome
{
    public:
        nome();
        void Set(string nome);
        string get();
    private:
        string name;
};

class telefone
{
    public:
        telefone();
        void Set(string t) throw (invalid_argument);
        string get();
    private:
        string tel;
};

class senha
{
    public:
        senha();
        void Set(string s) throw (invalid_argument);
        string get();
    private:
        string pass;
};

class matricula
{
    public:
        matricula();
        void Set(string z) throw(invalid_argument);
        string get();
    private:
        string mat;
};

class Email
{
    public:
        Email();
        void Set(string em) throw(invalid_argument);
        string get();
    private:
        string email;
};

class Custo
{
    public:
        Custo();
        void Set(float n) throw(invalid_argument);
        float get();
    private:
        float c;
};

#endif // DOMINIOS_H

Dominios.cpp

#include "Dominios.h"
#include <string.h>

using namespace std;

CodProjeto::CodProjeto()
{

}

void CodProjeto::Set(string x) throw (invalid_argument)
{
    unsigned int i = 0;
    string error = "Codigo invalido";

    if(x.length()!=5) throw invalid_argument(error);
    while((i!=x.length())&&(!isdigit(x.at(i)))){
        i++;
    }
    if(i!=x.length()) throw invalid_argument(error);
    this->cod = x;
}

string CodProjeto::get()
{
    return this->cod;
}

EstadoProjeto::EstadoProjeto()
{
    this->x = 0;
}

void EstadoProjeto::Set(int est) throw(invalid_argument)
{
    if((est==1)||(est==2)){
        this->x = est;
    }else throw invalid_argument("Estado Invalido");
}

int EstadoProjeto::get()
{
    return this->x;
}

FaseProjeto::FaseProjeto()
{
    this->x = 0;
}

void FaseProjeto::Set(int x) throw(invalid_argument){
    if((x > 0)&&(x < 5)){
        this->x = x;
    }else throw invalid_argument("Erro fase invalida");
}

int FaseProjeto::get(){
    return this->x;
}

Func::Func()
{
    this->x = 0;
}

void Func::Set(int x) throw(invalid_argument)
{
    if((x > 0)&&(x < 4)){
        this->x = x;
    }else throw invalid_argument("Erro funcao invalida");
}

int Func::get()
{
    return this->x;
}

data::data(){
    this->d = 0;
    this->m = 0;
    this->a = 0;
}

void data::Set(int d,int m,int a) throw(invalid_argument)
{
    if((d >= 1)&&(d <= 31)&&(m >= 1)&&(m <= 12)&&(a >= 2016)&&(a <= 2050)){
        this->d = d;
        this->m = m;
        this->a = a;
    }else throw invalid_argument("Erro formato invalido");
}

void data::Set(string d) throw(invalid_argument)
{
    int v;
    string error = "data invalida";

    try{
        this->verificaformato(d);   /*verifica o formato inserido,caso contrario lança a exceçao e essa mesma exceçao e lançada novamente*/
    }catch(invalid_argument e){
        throw invalid_argument(e);
    }
    v = this->calculadigito(d,2,0); /*chama a funçao calcular digito e retorna um int*/
    if((v>=1)&&(v<=31)){    /*testa o valor recebido e esse valor e colocado no objeto*/
        this->d = v;
    }else throw invalid_argument(error);    /*caso a condiçao nao seja satisfeita um erro sera lançado*/
    v = this->calculadigito(d,2,3);
    if((v>=1)&&(v<=12)){
        this->m = v;
    }else throw invalid_argument(error);
    v = this->calculadigito(d,4,6);
    if((v>=2016)&&(v<=2050)){
        this->a = v;
    }else throw invalid_argument(error);
}

int data::calculadigito(string d,int lim,int pos)   /*calcula o digito da string data*/
{ /*recebe uma posiçao da string um limite e a string*/
    int j = lim-1,i =0,z=0,result=0;    /*declaracao de variaveis*/

    for(i=0;i<lim;i++){
        z = d.at(pos) - '0';    /*z recebe um inteiro da string*/
        result += z * pow(10,(double)j);    /*resultado recebe o valor * 10 ^ j onde j corresponde ao numero de digitos do int*/
        j--;
        pos++;
    }
    return result;  /*retorna o valor da string calculado*/
}

void data::verificaformato(string d) throw(invalid_argument)    /*verifica se o formato esta correto*/
{
    int ns =0,brs = 0,i=0;
    string error = "Formato invalido";

    while(i!=(int)d.length()){
        if(isdigit(d.at(i))){
            ns++;   /*nrs representa a quantidade de numeros*/
        }else if(d.at(i)=='/'){
            brs++;  /*brs representa a quantidade de barras*/
        }else throw invalid_argument(error);
        i++;
    }
    if((ns!=8)||(brs!=2)) throw invalid_argument(error);
}

int data::getAno()
{
    return this->a;
}

int data::getDia()
{
    return this->d;
}

int data::getMes()
{
    return this->m;
}

string data::getDATA()
{
    string y;
    ostringstream x;
    x << this->d << "/" << this->m << "/" << this->a;
    y = x.str();
    return y;
}

nome::nome()
{

}

void nome::Set(string nome)
{
    unsigned int i=0;
    string error = "Erro nome invalido";

    if(nome.length() > 21) throw invalid_argument(error);
    while((i!=nome.length())&&(!isdigit(nome.at(i)))){
        i++;
    }
    if(i!=nome.length()) throw invalid_argument(error);
    this->name = nome;
}

string nome::get()
{
        return this->name;
}

telefone::telefone()
{

}

void telefone::Set(string t) throw(invalid_argument){
    unsigned int i=0;
    string error = "Erro telefone invalido";

    if(t.length()>8) throw invalid_argument(error);
    while(i!=t.length()){
        if(!isdigit(t.at(i))) throw invalid_argument(error);
        i++;
    }

    this->tel = t;
}

string telefone::get(){
     return this->tel;
}

senha::senha()
{

}

void senha::Set(string s) throw (invalid_argument)
{
    unsigned int i=0,k=0;
    string error = "Erro senha invalida";

    if(s.length()!=5) throw invalid_argument(error);
    while(k!=s.length()){
        i = k+1;
        while(i!=s.length()){
            if(s.at(i)==s.at(k)) throw invalid_argument(error);
            i++;
        }
        k++;
    }
    this->pass = s;

}

string senha::get()
{
    return this->pass;
}

matricula::matricula()
{

}

void matricula::Set(string z) throw(invalid_argument)
{
    unsigned int i=0;
    string error = "Erro matricula invalida";

    if(z.length()>5) throw invalid_argument(error);
    while(i!=z.length()){
        if(!isdigit(z.at(i))) throw invalid_argument(error);
        i++;
    }
    this->mat = z;
}

string matricula::get()
{
    return this->mat;
}

Email::Email()
{

}

void Email::Set(string em) throw(invalid_argument)
{
    unsigned int i = 0;
    string error = "Erro email invalido";

    while((i!=em.length())&&(em.at(i)!='@')){
        i++;
    }
    if(em.at(i)=='@'){
        while((i!=em.length())&&(em.at(i)!='.')){
            i++;
        }
        if(i==em.length()) throw invalid_argument(error);
        this->email = em;
    }else throw invalid_argument(error);
}


string Email::get()
{
    return this->email;
}

Custo::Custo()
{
    this->c = 0;
}

void Custo::Set(float n) throw(invalid_argument)
{
    if(n>0){
        this->c = n;
    }else throw invalid_argument("Custo invalido");
}

float Custo::get()
{
    return this->c;
}

codigo da classe(arquivo Entidades.h):

#ifndef ENTIDADES_H
#define ENTIDADES_H

#include "Dominios.h"
#include <string>
class GerSistema
{
    public:
        GerSistema();
        ~GerSistema();
        void SetNome(nome n);
        nome getNome();
        void SetMatricula(matricula m);
        matricula getMatricula();
        void SetSenha(senha s);
        senha getSenha();
    private:
        nome nome;
        matricula matricula;
        senha senha;
};
#endif // ENTIDADES_H

source onde as funções da classe estao sendo codificadas(arquivo Entidades.cpp)

#include "Entidades.h"

GerSistema::GerSistema()
{

}

GerSistema::~GerSistema()
{

}



void GerSistema::SetNome(nome n)
{
    this->nome = nome;
}

nome GerSistema::getNome()
{
    return this->nome;
}

o problema é quando eu faço desta maneira,passando o objeto e declarando ele na classe da esse erro

C:\Users\Renan\Documents\projetos C++\trabalho1tp11\src\Entidades.cpp|13|error: variable or field 'SetNome' declared void|

C:\Users\Renan\Documents\projetos C++\trabalho1tp11\src\Entidades.cpp|13|error: expected primary-expression before 'n'|

alguém sabe uma maneira de contornar este problema?obg quem puder me responder

9
  • Qual é a linha 13?
    – Maniero
    14/09/2016 às 20:25
  • é a linha onde está a função GerSistema::SetNome na source que eu postei em baixo
    – ReZ
    14/09/2016 às 20:29
  • nome é um tipo? Onde está a definição dele? O código está muito confuso. Eu não estou entendendo bem o que tem aí, talvez até o compilador não esteja.
    – Maniero
    14/09/2016 às 20:30
  • não é um tipo,é uma classe,mas especificamente um objeto,eu estou tentando passa-lo como parametro pra essa funçao
    – ReZ
    14/09/2016 às 20:31
  • 1
    Uma classe é um tipo. Você precisa colocar mais informações, o problema pode estar em outro lugar, de qualquer forma, o parâmetro é n, depois usa dentro nome, claro que não funciona, mas nem acho que seja esse erro, esse é outro. Eu começaria reduzir a confusão e dar nomes melhores para os tipos seguindo uma nomenclatura padrão.
    – Maniero
    14/09/2016 às 20:33

2 Respostas 2

3

O problema é o uso dos mesmos identificadores para nomes de classe e de variáveis. Isso deixou o compilador confuso...

Mudando nome para nome_, matricula para matricula_, e senha para senha_ passou a compilar sem problemas.

Em Entidades.h

private:
    nome nome_;
    matricula matricula_;
    senha senha_;

Em Entidades.cpp

void GerSistema::SetNome(nome n)
{
    // this->nome = nome; // isso estava errado, devia ser "...= n"
    this->nome_ = n;
}

nome GerSistema::getNome()
{
    return this->nome_;

Agora, esse código todo é horroroso e ineficiente, deve ter sido copiado de Java ou C#, ninguém programa em C++ assim...praticamente todas as funções que recebem objetos como parâmetros deveriam usar passagem de parâmetros por referência, e as funções de consulta deveriam retornar referências, não uma cópia do objeto. Além disso não é comum utilizar a notação this->xxx, usa-se simplesmente xxx.

void GerSistema::SetNome(nome& n)
{
   nome_ = n;
}
4
  • vlw kara,eu tinha deixado com o mesmo nome do tipo para que não ficasse muito confuso na hora de alterar os valores das variaveis,vlws
    – ReZ
    14/09/2016 às 23:38
  • O +1 vai especialmente para o último parágrafo. Na tentativa de deixar menos confuso, o código ficou altamente confuso. Mas quase não dei o +1 pelo underline que eu odeio :P
    – Maniero
    14/09/2016 às 23:43
  • @bigown Eu também não uso underline, mas foi uma maneira de mexer o menos possível no código original. E quanto ao underline, goste-se ou não, é uma convenção bem conhecida, e razoavelmente bem utilizada.
    – zentrunix
    15/09/2016 às 0:45
  • Eu sei, eu é que não gosto mesmo.
    – Maniero
    15/09/2016 às 0:55
1

blz,consegui resolver o problema,para quem tiver com o mesmo problema,a unica maneira(pelo menos a que eu encontrei),foi codificar a função na assinatura dela existente na classe

basicamente:

#ifndef ENTIDADES_H
#define ENTIDADES_H

#include "Dominios.h"
#include <string>
class GerSistema
{
    public:
        GerSistema();
        ~GerSistema();
        void SetNome(nome n){this->nome = n;}
        nome getNome();
        void SetMatricula(matricula m);
        matricula getMatricula();
        void SetSenha(senha s);
        senha getSenha();
    private:
        nome nome;
        matricula matricula;
        senha senha;
};
#endif // ENTIDADES_H

ao invés de codificar a função em um arquivo cpp separado com a biblioteca da classe incluida,basta codifica-la na propria assinatura da classe na sua biblioteca de classes,que esse erro some,porém não acho que seja uma solução conveniente ja que é necessario acessar a biblioteca para poder editar a função em caso de erros no algoritmo,se alguém souber alguma solução melhor e puder responder poste aqui,vlws pessoal ;D

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .