How can I “double-load” an operator?

If I have a class similar to a database and I want to do something like this:

object [1] == otherObject;

How can I "double-load" the [] operator and the == operator?

+3
source share
4 answers

object[1]returns an object someType. You need to reload operator==on someType.

+8
source

What you are describing is just two separate operator overloads. Just make sure the parameter operator ==matches the return type operator [].

+2
source

, , . ; . , operator[] -. - operator== . , std:: map operator [] , .

(, , [1] 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);

: , (- ), , Foo, , , : operator==, operator[] .

, SomeProxy private . , : ( []), ( ), Foo/ , .

+2

- , . , , , , . ( 2 . , .)

:

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 a type Aobject with a type object B. It will also allow you to compare a type Aobject with a type object C.

+1
source

Source: https://habr.com/ru/post/1752938/


All Articles