Compiler error when using nested operator overloading in C ++
I have a URL class that overloads the ==, <,>, and! = Operators for simple comparison. The URL class has a string data member and some string functions. The operators work great when testing with the URL class.
I also have a page class that has a URL data member. I am trying to overload the same operators in the Page class. The equality in the page class is based on the equality of their respective urls, so I use the url class boolean operators to compare pages. This creates some compiler errors that I cannot understand. Code for URL operators:
bool URL::operator ==(URL & u) const {
//url is the string instance variable
return url == u.GetURL();
}
Code for page operators:
bool Page::operator ==(Page & p) const {
//url is the URL instance variable of the Page class
return url == p.GetURL();
}
This leads to the following errors:
src/Page.cpp: In member function ‘bool Page::operator==(Page&) const’:
src/Page.cpp:21: error: no match for ‘operator==’ in ‘((const Page*)this)->Page::url == Page::GetURL()()’
inc/URL.h:118: note: candidates are: bool URL::operator==(URL&) const
I predict that it is something dumb that I forget. Will you prove that I'm right?
edit: Fixed a bug in the ass. Thanks for the help.
source to share
Should be:
bool URL::operator ==(const URL & u) const {
//url is the string instance variable
return url == u.GetURL();
}
And similarly for other operators.
If you are still getting compiler errors, you may not have made GetURL()
const either :
std:string URL::GetURL() const {
// whatever...
}
source to share
I would also like to point out that there are methods (i.e. public interface) to protect external objects from changes in implementation details. Also that the class is automatically a friend to itself (for the same reason) and thus just accessing the members of another object is fine.
bool URL::operator ==(URL & u) const {
//url is the string instance variable
return url == u.GetURL();
}
You can write like this:
bool URL::operator ==(URL & rhs) const
{
return url == rhs.url; // No need to use GetURL()
}
In my opinion, this makes the code clearer (but this is again an opinion that your taste may have)
source to share