Reputation: 17
I got this function:
bool operator==(const foo& foo1, const foo& foo2)
how do I compare the two objects with each other, is there a library function that allows me to doit? or do I have to physically compare each of the variables inside the objects.
EDIT:
foo
object holds:
private:
int *values;
size_t *columns;
std::map< size_t, std::pair<size_t, unsigned int> > maps;
Upvotes: 0
Views: 5582
Reputation: 1
bool operator ==(const Student &first, const Student &second)
{
return (first.rollno == second.rollno && first.str == second.str);
}
class Student
{
public:
string str;
int rollno;
Student(string str1,int rollno1)
{
str=str1;
rollno1=rollno;
}
};
cout <<"is s1=s2? \n" << boolalpha << operator==(s1,s2) <<endl;
Upvotes: 0
Reputation: 3795
The signature of the overloaded operator you have is for a static function defined outside of the foo
class. Since you stated that the data members of foo
are declared as private
, you're going to have a tough time getting your operator to work.
If you are required to use that signature for your homework, you need to research the friend
keyword...after all, it is homework, nobody's going to do it for you.
If not, consider making the operator a member of the foo
class. This is a great general reference for operator overloading.
Upvotes: 0
Reputation: 11892
It is dependant on the class foo
and what data members it has, and what a vaild equality is. Imagine you foo
is the following:
class foo {
private:
long id;
...
};
If you wanted to compare based on the id
field:
bool operator==(const foo& foo1, const foo& foo2) { return foo1.id == foo2.id; }
They can be as simple or complicated as your needs require.
Upvotes: 0
Reputation: 320747
The semantics of the comparison function depends on your intent and in the nature and semantics of object's internals. In your case only you know what foo
is and, therefore, only you know how to properly compare one foo
object to another foo
object. There's no universal one-fits-all answer to your question.
Upvotes: 5
Reputation: 75150
You have to go through and compare the variables inside yourself.
That way, you define what equality is. If foo
represents a person, you can define two foo
s as equal by just the first name, or by first and last name, or by social security number, or whatever you want. Only you, as the writer of the class, know what it means for two of your objects to be equal.
Upvotes: 2