Struct with union is giving invalid use error

1

I need to use union within struct , but I can not. The error displayed is

  

[Error] invalid use of 'union Client :: document'

Struct:

struct Cliente{
       string nome, email;
       union documento{
             long cpf,cnpj;
       };
};

Function:

void cadastrarCliente(Cliente *cli){
     fstream aCliente;
     aCliente.open("clientes.txt", ios::out|ios::app); 
     aCliente << cli->documento << " " << 
                 cli->nome << " " << 
                 cli->email << "\n";
     aCliente.close();         
}
    
asked by anonymous 18.11.2018 / 14:18

1 answer

0

First, you do not seem to need a union . To begin CNPJ and CPF are descriptive data and should be strings and not numbers , the which already kills the need to union.

union with two fields of the same type does not make much sense. Just to use a different name? I see no advantage in C. In C ++, it has better mechanisms. Anyway, it's not even what you need.

A% with no tag , one of the criticisms of the C mechanism is not useful, so C ++ has better structures in the library than union , if it were required. But of course you can always use an extra tag in the union itself to know what to get in each case, just have the problem that this is an abstraction leak.

struct was created to solve lower-level issues, it seems to me that it's mixing different levels of abstraction.

For all this I prefer to either try to solve your specific problem and solve the real problem that is broader. Solving the question problem is a palliative that will still keep it wrong in the overall concept.

If you do it right you will only have the space for the string of the CNPJ which is bigger, and of course, an extra tag that seems fundamental to me anyway in that register. This is a case where putting the string inline in union seems appropriate.

Strongly question whether to use struct to struct . But okay, it's just a start, and technically will change little use for a class, it will only give a more appropriate semantics, and will further indicate that this should probably be a type by reference. But I will not dwell on it because at the moment it is too simple a code.

That would be a better solution:

struct Cliente {
    string nome, email, tipo, documento;
};

It has other issues that probably indicate that the code is mixing C with C ++ and is the way of the last century to do in C ++.

    
18.11.2018 / 14:47