简体   繁体   中英

'static' keyword for binary operator declarations

In C++, binary operators can either be overriden with one or two operators, when the LHS is the class being declared. If declared with two parameters in must be a non-member function. Vis in this code, the two declarations are identical.

class MyClass
{
     public:
         MyClass operator+(const MyClass&);
}
MyClass operator+(const MyClass&, const MyClass&);

Is there a reason the latter can not be done as a static member function? Like this

class MyClass
{
     public:
         static MyClass operator+(const MyClass&, const MyClass&);
}

It would make writing the stream in/out operators easier (I am aware you can use friend to declare the operator)

The logic is that a+b can be interpreted as operator+(a,b) or as a.operator+(b) , each of which looks plausible if you squint. The former can't find any member functions; the latter could find static ones, but would uselessly pass only b to them. A static one could be called properly via an interpretation as a.operator+(a,b) , but that would attempt to pass an extra argument to any non-static member (possibly turning a unary - into a binary one, for instance). It would also defeat the feature of allowing conversions on the first argument, since its (original) type would restrict the candidates via name lookup.

There is one case where operator+(a,b) could find a member function—when the operator itself appeared in a class (member function). The unqualified lookup for such a name specially ignores class members because they (non-static as they are) would have the wrong arity and (very often) would be for the wrong type (shadowing all non-member functions for the same operator!).

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