pass objects as parameters in c++

Asked

Viewed 2,002 times

1

hello, I would like to know how to pass an object created in c++ as parameter of a function of another object,vi in the forum in English,but I did not understand very well how it does,if someone can help me,

classes I’m using on the object

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;
}

class code(Entities file. 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 where the class functions are being encoded (Entities.cpp file)

#include "Entidades.h"

GerSistema::GerSistema()
{

}

GerSistema::~GerSistema()
{

}



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

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

the problem is when I do so,passing the object and declaring it in class of that error

C: Users Renan Documents projects C++ work1tp11 src Entities.cpp|13|error: variable or field 'Setnome' declared void|

C: Users Renan Documents projects C++ work 1tp11 src Entities.cpp|13|error: expected Primary-Expression before 'n'|

anyone knows a way around this problem? obg who can answer me

  • What is line 13?

  • is the line where is the function Gersistema::Setnome in the source I posted below

  • nome is a type? Where is the definition of it? The code is very confusing. I’m not sure what is there, maybe even the compiler is not there.

  • it’s not a type, it’s a class, but specifically an object,

  • 1

    A class is a type. You need to put more information, the problem may be elsewhere, either way, the parameter is n, then use inside nome, Of course it doesn’t work, but I don’t even think it’s that mistake, that’s another. I would begin to reduce confusion and give better names to the types by following a standard nomenclature.

  • I’ll edit and update the code, to be clearer

  • If you make a [mcve] even better

  • The includes would also be very precious.

  • blz, I think ta best,to visualize Edit:ignore some of the comments I made,

Show 4 more comments

2 answers

3


The problem is the use of the same identifiers for class and variable names. This left the compiler confused...

Changing nome for nome_, matricula for matricula_, and senha for senha_ started to compile without problems.

In Entities. h

private:
    nome nome_;
    matricula matricula_;
    senha senha_;

In Entities.cpp

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

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

Now, this whole code is horrific and inefficient, it must have been copied from Java or C#, no one programs in C++ so...virtually all functions that receive objects as parameters should use parameter passing by reference, and the query functions should return references, not a copy of the object. Furthermore, it is not common to use the rating this->xxx, is simply used xxx.

void GerSistema::SetNome(nome& n)
{
   nome_ = n;
}
  • vlw kara,I had left with the same name of the type so that it was not too confused when changing the values of the variables,vlws

  • The +1 goes especially to the last paragraph. In an attempt to make it less confusing, the code became highly confused. But I almost did not give the +1 for the underline that I hate :P

  • @bigown I also do not use underline, but it was a way to mess as little as possible in the original code. And as for the underscore, like it or not, it’s a well-known convention, and reasonably well used.

  • I know, I just don’t like it.

1

blz,I was able to solve the problem,for anyone with the same problem,the only way(at least the one I found),was to encode the function in her signature existing in the class

basically:

#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

instead of encoding the function in a separate cpp file with the included class library, simply encode it in the class signature itself in its class library, some, however I do not think it is a convenient solution since it is necessary to access the library to be able to edit the function in case of errors in the algorithm, if someone knows a better solution and can answer post here,vlws personal ;D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.