Problem with struct in C ++


What type of error or omission am I committing in the code?

Specifically in the statement% main% co_. Error which I have solved comparing the results one by one, which would be problematic when you have to compare more than 3 variables.

using namespace std;

struct persona{
    string nombre, pat, mat;

int main(){
    persona a,b;

    b.nombre = "luz";
    b.pat = "dia";
    b.mat = "noche";

    cout<<"ingrese su nombre : ";
    cout<<"ingrese su apellido paterno : ";
    cout<<"ingrese su apellido materno : ";

    if(a == b)cout<<"son la misma persona.";//aqui tengo el problema. Siento de que se me olvida algo...
        else cout<<"son diferentes personas.";

Here is how I resolved it.

if(a.nombre == b.nombre){
   if(a.pat == b.pat){
      if(a.mat == b.mat)cout<<"son la misma persona.";
   else cout<<"son diferentes personas.";
else cout<<"son diferentes personas.";
asked by bassily 23.06.2016 в 01:25

3 answers



answered by 23.06.2016 / 09:31

I think what you're looking for is called "operator overload"

It would be redefining the operator == for that type of object, something similar to this:

bool operator == (persona &p1,persona &p2)
    return (p1.nombre==p2.nombre&&p1.pat==p2.pat&&p1.mat==p2.mat);

Look it up in google, it should not be hard to find information.

answered by 23.06.2016 в 02:15

We are going to avoid a complicated issue such as operator overload and create a function that helps us evaluate each value in the struct:

bool equals(persona _a, persona _b)
    return (_a.nombre == _b.nombre) 
        && (_a.mat == _b.mat)
        && (_a.pat == _b.pat);
     // && (_a.<otravariable> == _b.<otravariable>)

As you can see, we are creating a function of type bool that is evaluated by each member within the type instance persona that we send.

To verify that all members are equal, the operator && (Y) is used to link conditions.

Applied to your code:

if(equals(a, b)) cout<<"son la misma persona."; // No deberia haber error...

While with operator overload, it's something like what Arnau has mentioned.

In the end you will always compare each of the values manually, but there are processes that allow the simplification of this comparison.

I hope it has helped you!

answered by 23.06.2016 в 03:20