29. Overloaded functions in classes

The essence of function overloading is that different functions are opposed to each other. In C++, the function call is determined by the function name and function parameters, and the entry address of the overloaded function cannot be obtained directly through the function name. Function overloading must occur in the same scope.

Member functions in a class can be overloaded:

    constructor overloading,

    Overloading of ordinary functions,

    Overloading of static members.

Static member functions and ordinary member functions can be overloaded, and class member functions can be overloaded.

#include <stdio.h>
class Test
{
    int i;
public:
    Test()
    {
        printf("Test::Test()\n");
        this->i = 0;
    }
    
    Test(int i)
    {
        printf("Test::Test(int i)\n");
        this->i = i;
    }
    
    Test(const Test& obj)
    {
        printf("Test(const Test& obj)\n");
        this->i = obj.i;
    }
    static void func()
    {
        printf("void Test::func()\n");
    }    
    void func(int i)
    {
        printf("void Test::func(int i), i = %d\n", i);    int getI ()
    }
    

    {
        return i;
    }
};
void func()
{
    printf("void func()\n");
}
void func(int i)
{
    printf("void func(int i), i = %d\n", i);
}
int main()
{
    func();
    func(1);
    Test t;        // Test::Test()
    Test t1(1);    // Test::Test(int i)
    Test t2(t1);   // Test(const Test& obj)   
    func();        // void func()
    Test::func();  // void Test::func()    
    func(2);       // void func(int i), i = 2;
    t1.func(2);    // void Test::func(int i), i = 2
    t1.func();     // void Test::func()    
    return 0;

}

The meaning of overloading: the function function is prompted through the function name, the function usage is prompted through the parameter list, and the function functions that already exist in the system are extended.

#include <stdio.h>
#include <string.h>
char* strcpy(char* buf, const char* str, unsigned int n)
{
    return strncpy(buf, str, n);
}
int main()
{
    const char* s = "D.T.Software";
    char buf[8] = {0};
    //strcpy(buf, s);
    strcpy(buf, s, sizeof(buf)-1);
    printf("%s\n", buf);
    return 0;

}

Member functions of a class can be overloaded, and overloading must occur in the same scope. Global functions and member functions cannot constitute an overloading relationship.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325883641&siteId=291194637