If I have a database-like class, and I want to do something like this:
object[1] == otherObject;
How do I "double overload" operator[] and o开发者_C百科perator==?
object[1]
returns an object of someType
. You need to overload operator==
on that someType
.
What you describe is simply two separate operator overloads. Just make sure that the parameter to operator ==
matches the return type of operator []
.
I was really confused at first by the wording of the question, but now I think I understand. You can't do this directly; but you can achieve the same effect. The idea is to make operator[]
return a proxy object. For the proxy object, you can provide operator==
with custom behavior for comparison. I've seen std::map's operator[] implemented this way on some older, more obscure standard library implementations.
Example (let's say object[1] normally returns Foo&):
class SomeProxy
{
private:
Foo* f;
public:
explicit SomeProxy(Foo& i_f): f(&i_f) {}
operator Foo&() const {return *f;}
};
SomeProxy Database::operator[](unsigned int n)
{
return SomeProxy(some_array + n);
}
bool operator==(const SomeProxy& lhs, const Foo& rhs)
{
// provide custom behavior
}
// also provide custom behavior for these:
bool operator==(const SomeProxy& lhs, const SomeProxy& rhs);
bool operator==(const Foo& lhs, const SomeProxy& rhs);
Note: it seems kind of odd that you want to overload the meaning of a comparison operator in such a case (proxy objects are often used for custom assignment behavior with associative structures or for fancy metatemplate programming) but for comparison they should typically provide the same meaning as working with Foo
directly, e.g. Nevertheless, here's the way to do it: a way to get custom behavior through operator==
that is only applicable when using an overloaded operator[]
in the same expression.
If you want to make this thorough, then make the constructors of SomeProxy private and make Database a friend. This way, only the Database: can create those objects (through operator[] in this case) and the client won't be able to copy it (which he shouldn't), only get a Foo object/reference out of it or use the proxy returned in an expression.
Don't think of operator overloading as anything special, they are just like normal function overloading. Two functions having the same name can be overloaded given that they have different signatures. (You can't overload 2 functions only by the return type by the way. That is not just for operator overloading, it is for all overloading of functions in general.)
So simply like this:
class B {};
class C {};
class A
{
bool operator==(const B& b)
{
//Put logic here
return true;
}
bool operator==(const C& c)
{
//Put logic here
return true;
}
};
The above code will allow you to compare an object of type A
with an object of type B
. It will also allow you to compare an object of type A
with an object of type C
.
精彩评论