简体   繁体   中英

Functions that cannot be overloaded in C++

Member function declarations with the same name and the name parameter-type-list cannot be overloaded if any of them is a static member function declaration. For example, following program fails in compilation.

#include<iostream> 
class Test { 
   static void fun(int i) {} 
   void fun(int i) {}    
}; 
  
int main() 
{ 
   Test t; 
   getchar(); 
   return 0; 
} 

I don't understand why the following example can run:

#include<iostream> 
class Test {
public:
    static void fun(double i) {
        std::cout << i << "\n";
    }

    void fun(int i) {
        std::cout << i;
    }
};

int main()
{
    Test t;
    t.fun(5.5);
    t.fun(4);
    return 0;
}

The second Example will run because the parameter types are different in both the function, ie double in the first and int in second. So function overloading takes place

Function overloading only works when you have different set of parameters, in the example's case it's int and double. change the parameter data type.

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