Reputation: 95
I made a simple struct
named coord to hold , well coordinates , and I wanted to check if two coords were equal , so I looked how to do a proper operator overloading in another thread and came up with this :
#include <iostream>
using namespace std;
struct coord{
int x;
int y;
inline bool operator==(const coord& lhs, const coord& rhs){
if(lhs.x == rhs.x && lhs.y == rhs.y){
return true;
}
else{
return false;
}
}
};
int main(){
coord a,b;
a.x=5;
a.y=5;
b.x=a.x;
b.y=a.y;
if(a==b){
cout<<"Working"<<endl;
}
return 0;
}
But at compiling I get a massive error who looks like :
g++ -c -o obj/main.o main.cpp -I../include
main.cpp:8:62: error: ‘bool coord::operator==(const coord&, const coord&)’ must take exactly one argument
inline bool operator==(const coord& lhs, const coord& rhs){
^
main.cpp: In function ‘int main()’:
main.cpp:24:6: error: no match for ‘operator==’ (operand types are ‘coord’ and ‘coord’)
if(a==b){
^
main.cpp:24:6: note: candidates are:
In file included from /usr/include/c++/4.9.2/iosfwd:40:0,
from /usr/include/c++/4.9.2/ios:38,
from /usr/include/c++/4.9.2/ostream:38,
from /usr/include/c++/4.9.2/iostream:39,
from main.cpp:1:
/usr/include/c++/4.9.2/bits/postypes.h:216:5: note: template<class _StateT> bool std::operator==(const std::fpos<_StateT>&, const std::fpos<_StateT>&)
operator==(const fpos<_SenttateT>& __lhs, const fpos<_StateT>& __rhs)
^
This goes on for a variety of other std things as ‘coord’ is not derived from ‘const std::basic_string<_CharT, _Traits, _Alloc>’
or ‘const std::allocator<_CharT>’
, the whole error being to long here it is on pastebin.
I hope someone understands whats going wrong here and can explain it to me
Upvotes: 0
Views: 93
Reputation: 206737
There are couple of choices to get around the problem:
Member function
inline bool operator==(const coord& rhs) const {
return (this->x == rhs.x && this->y == rhs.y);
}
When you use
if(a==b){
the function is called on the object a
and the argument to the function is b
.
Non-member function
This can be defined outside the definition of struct coord
.
struct coord{
int x;
int y;
};
bool operator==(const coord& lhs, const coord& rhs){
return (lhs.x == rhs.x && lhs.y == rhs.y);
}
When you use
if(a==b){
the function is called with a
for lhs
and b
for rhs
.
Upvotes: 5