newbie: operator == and !=

A

andrew_nuss

Hi,

I have a simple struct:

struct Snippet {
// only data member
int* ar;

// member functions such as:
Snippet (int* array) : ar(array) {}
};

And it is the case that if I have 2 Snippets, they are the same if and
only if the "ar"
members are the same physical array pointer.

My question concerns the default == operator and != operator. Are the
sufficient to mean
"same/not same" reference to physical array? What custom operators
should I define?

main {
int ar[] = {1,2,3};
Snippet s1 = Snippet(ar);
Snippet s2 = Snippet(ar);
bool same = s1 == s2; //true???, fast???
bool diff = s1 != s2; // false???, fast???
}

Thanks,
Andy
 
R

Ron Natalie

And it is the case that if I have 2 Snippets, they are the same if and
only if the "ar"
members are the same physical array pointer.

OK, but that's going to be a problematic design.

You need to define both operator== and operator!= that takes
two snippets.
My question concerns the default == operator and != operator.

There's no such thing as a default == or != operator. If you
don't define them, you can't apply those operators to Snippet.
 
I

ivan.leben

And it is the case that if I have 2 Snippets, they are the same if and
only if the "ar"
members are the same physical array pointer.

My question concerns the default == operator and != operator. Are the
sufficient to mean
"same/not same" reference to physical array? What custom operators
should I define?

main {
int ar[] = {1,2,3};
Snippet s1 = Snippet(ar);
Snippet s2 = Snippet(ar);
bool same = s1 == s2; //true???, fast???
bool diff = s1 != s2; // false???, fast???
}

Thanks,
Andy

Yes you have to define == and != operators in order to use them that
way. The trick to get this work fast is to pass the operands to the
operator function by reference instead of by value which would involve
copying of the data. Additionally you want this reference to be const
so you assure that the passed operands will not be changed by the
operator:

struct Snippet {
char *ar;

bool operator== (const Snippet &s) {
return ar == s.ar;
}

bool operator!=(const Snippet &s) {
return ar != s.ar;
}
};
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top