开发者

learning about function prototypes and function overloading

开发者 https://www.devze.com 2023-01-21 13:56 出处:网络
can anyone give me an example of function overloading in c++ with 4 function prototypes ? i still don\'t get them quite good ..

can anyone give me an example of function overloading in c++ with 4 function prototypes ? i still don't get them quite good ..

sorry newbie question, thanks for looking in.

开发者_如何学编程

Adam Ramadhan


The following are C++ function declarations and would typically be in the header (.h or .hpp) file. These particular declarations have no code. The code is in the definition shown further below.

int sum(int a, int b);
int sum(int a, int b, int c);
int sum(int a, int b, int c, int d);
int sum(int a, int b, int c, int d, int e);

The above four functions have the same name, but the C++ compiler will call the one whose parameter signature matches the one in the calling code. The purpose of a declaration is to tell the compiler what the return type and parameter signature of a function are. If more than one function has the same name but differs in its parameter signature, it is referred to as overloaded. This is a C++ feature not present in C. Note that the return type cannot be used to differentiate overloaded functions.

The following are the definitions (implementations) of the overloaded functions and would typically be in the module (.cpp or .cc or .cxx) file. This is where the executable code resides between the braces { } that surround the function block:

int sum(int a, int b)
{
    return (a + b);
}

int sum(int a, int b, int c)
{
    return (a + b + c);
}

int sum(int a, int b, int c, int d)
{
    return (a + b + c + d);
}

int sum(int a, int b, int c, int d, int e)
{
    return (a + b + c + d + e);
}

Usage example:

std::cout << sum(3, 4, 5) << std::endl;

will invoke the code for the second overloaded function listed above that takes three int parameters.

0

精彩评论

暂无评论...
验证码 换一张
取 消