#include <iostream>
using namespace
class Book{
string title;
int price, pages;
public:
Book(string title = "", int price = 0, int pages = 0){
this->title = title;
this->price = price;
this->pages = pages;
}
bool operator==(Book);
};
bool Book::operator==(Book op1){
if(*(this) == op1)
return true;
else
return false;
}
int main()
Book a("Good C ", 30000, 500), b("Bad C ", 30000, 500);
if (a == b)
cout << "Same books" << endl;
}
When run the code. I get the following error
zsh: segmentation fault ./main
How can I compare two objects?
this == op1
I tried this, but an error occurred because the data format is different
CodePudding user response:
You need to actually perform the comparison within the operator. The way you had it, the == operator calls itself, which would end up causing a crash.
class Book{
string title;
int price, pages;
public:
Book(string title = "", int price = 0, int pages = 0){
this->title = title;
this->price = price;
this->pages = pages;
}
bool operator==(const Book&) const;
};
bool Book::operator==(const Book& op1) const{
return title == op1.title &&
price == op1.price &&
pages == op1.pages;
}
CodePudding user response:
bool Book::operator==(Book &op1){
if(*(this) == op1) // this lines calls the operator== function again.
return true;
else
return false;
}
The mentioned code is the wrong way of comparing objects. The above code keeps on calling the operator == again and again which result in segmentation fault
You have to compare each attributes(or any number of attribute as per requirement). The above code can be rewritten as:
bool Book::operator==(const Book& op1) const{
return (title == op1.title && price == op1.price && pages == op1.pages);
}
CodePudding user response:
Since C 20 you can put:
bool operator== (const Book&) const = default;
which does the same comparison you were trying to code.
You can write auto operator<=>
instead of bool operator==
to get all the relational comparison operators as well.
Prior to C 20 you can still keep your code tidy using tie
to combine all the members into one expression:
bool Book::operator==(const Book& op1) const
{
return std::tie(title, price, pages) == std::tie(op1.title, op1.price, op1.pages);
}