简体   繁体   中英

Operator overloading for primitive types in C++

In C++, if you've got a class Foo, and you want users of Foo to be able to write:

Foo x;
x += 3;

, you can simply make a member function of Foo, Foo& operator+=(int rhs) . If you want to be able to write:

Foo x;
int y = 3;
y += x;

, you cannot accomplish this by writing a member function of Foo, instead one has to write an external function, which usually must be declared as a friend of Foo.

How hard would it be for a future version of C++ to say that this can be written with a Foo member function int& operator+=(int &lhs, Reversed) , where Reversed was some empty class whose sole purpose was to distinguish the two versions of the operator?

If this were done, it could probably eliminate the vast majority of the uses of the friend keyword in new code.

You can in fact define such an operator, because you are free to overload += for built-in types:

int& operator+=(int &lhs, Foo &rhs) {
  lhs += rhs.somefield;
  return lhs;
}

On the other hand, instead of writing overloaded functions for all possible operators, you can also provide a function that will allow implicit casts of class Foo to int :

class Foo {
  ... somefield;

  operator int() {
    return (int)somefield;
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM