Why cant i use two ptrs in operator overload?
This is annoying, i can write a function with these parameters/return, but why cant i define an operator to do this?
-edit- i am actually trying to overload <<
the below is just for reference.
From msdn
// C2803.cpp
// compile with: /c
class A{};
bool operator< (const A *left, const A *right); // C2803
// try t开发者_StackOverflow社区he following line instead
// bool operator< (const A& left, const A& right);
gcc error
error: ‘bool operator<(const A*, const A*)’ must have an argument of class or enumerated type
Because every user-defined operator overload needs at least one user-defined type as a parameter. A point isn't a user-defined type.
C++03 standard, §13.5 [over.oper] p6
:
An operator function shall either be a non-static member function or be a non-member function and have at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration.
Because you aren't allowed to cheat.
If you could override comparison operators for pointer types, then you would no longer be able to compare those pointers by value (aka: by the actual numerical pointer values). And that's kind of important and occasionally useful.
My real code is actually <<. Why cant i use it for that?
For the same reason: pointers are C++-basic types. They aren't user-defined types. Do you want to be able to not left-shift pointer values anymore? OK, obviously you do, but C++ won't let you.
You can only override operators when C++ does not have existing functionality for operators with those types (with a few exceptions). C++ already has operator< and operator<< for pointers, so you're not allowed to change what they do.
精彩评论