How to call an operator as function in C++

后端 未结 6 2217
执念已碎
执念已碎 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:24

    The syntax of specifying a function as

    ::
    

    is used when Method() is a static method in Class. If Method() is a instance method, then the invocation is on a class object.

    Class classObject;
    classObject.Method()
    

    In this particular case, the declaration and usage of the operator+() method does not match.

    So, one approach would be to make the operator+() method static. But, I think, operator methods can only be non-static member function or non-member function.

    With all these knowledge, here is a full illustrative program.

    #include 
    
    struct B {
        int num_;
    
        B(int num) : num_( num ) {
        }
    
        static B add( const B & b1, const B & b2 ) {
            return B( b1.num_ + b2.num_ );
        }
    
        B operator+( const B & rhs ) {
            return B( num_ + rhs.num_ );
        }
    };
    
    int main() {
        B a(2), b(3);
    
        B c = B::add( a, b );
        assert( c.num_ == 5 );
    
        B d = a + b;
        assert( d.num_ == 5 );
    }
    

    The add() function is for example only, don't do it though.

提交回复
热议问题