How to call an operator as function in C++

后端 未结 6 2247
执念已碎
执念已碎 2021-02-19 11:04

I want to call a specific operator of specific base class of some class. For simple functions it\'s easy: I just write SpecificBaseClass::function( args );. How sho

6条回答
  •  无人共我
    2021-02-19 11:15

    The operator is a nonstatic member function, so you could use

    a.A::operator+( b )
    

    However, for another class that defines operator+ as a static member function, what you tried would be correct. And a third class might make it a free function (arguably the best way), so B::operator+(a,b) and a.operator+(b) would both be incorrect and operator+(a,b) would be right.

    Generally it's best just to use operator syntax a+b unless you know exactly what class it is, and that its implementation will never change. In a template context, writing a+b is a must, and it's essentially impossible to take the address of the overload (the only task that requires naming it) without a lot of work.

    In your context (a comment to another answer mentions templates), the best solution is

    c = static_cast< A const & >( a ) + static_cast< A const & >( b );
    

    … the problem is solved by slicing the types to reflect the subproblem, not precisely naming the function you want.

提交回复
热议问题