Overloading operators in derived class

前端 未结 3 2021
粉色の甜心
粉色の甜心 2020-12-31 07:46

Must I need to redefine all the overloading operators with derived type if I require to use them in derived class?

The following code compiles fine:

         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-31 08:20

    Overloading operators in derived class from IBM.

    A member function named f in a class A will hide all other members named f in the base classes of A, regardless of return types or arguments. The following example demonstrates this:

    struct A {
      void f() { }
    };
    
    struct B : A {
      void f(int) { }
    };
    
    int main() {
      B obj_B;
      obj_B.f(3);
    //  obj_B.f();
    }
    

    The compiler would not allow the function call obj_B.f() because the declaration of void B::f(int) has hidden A::f().

    To overload, rather than hide, a function of a base class A in a derived class B, you introduce the name of the function into the scope of B with a using declaration. The following example is the same as the previous example except for the using declaration using A::f:

    struct A {
      void f() { }
    };
    
    struct B : A {
      using A::f;
      void f(int) { }
    };
    
    int main() {
      B obj_B;
      obj_B.f(3);
      obj_B.f();
    }
    

    So if you do not overload all of them, then only the overloaded functions will be used.

提交回复
热议问题