码迷,mamicode.com
首页 > 编程语言 > 详细

C++之函数重载

时间:2015-11-07 20:38:48      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

C++的重载

In some programming languages, function overloading or method overloading is the ability to create multiple methods of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context.

For example, doTask() and doTask(object O) are overloaded methods. To call the latter, an object must be passed as a parameter, whereas the former does not require a parameter, and is called with an empty parameter field. A common error would be to assign a default value to the object in the second method, which would result in an ambiguous call error, as the compiler wouldn‘t know which of the two methods to use.

Another appropriate example would be a Print(object O) method. In this case one might like the method to be different when printing, for example, text or pictures. The two different methods may be overloaded as Print(text_object T); Print(image_object P). If we write the overloaded print methods for all objects our program will "print", we never have to worry about the type of the object, and the correct function call again, the call is always: Print(something).

以下程序实现了函数的重载。

#include <stdlib.h>
#include <iostream>
using namespace std;
void fun(int i=30, int j=20, int k=10);
int main(void)
{
	fun();
	fun(100);
	fun(100, 200);
	fun(100, 200, 300);
	system("pause");
	return 0;


}
void fun(int i, int j, int k)
{
	cout << i <<","<< j <<","<< k<<endl;
}

程序中,同名函数,函数参数的个数不同,运行结果:

技术分享

C++之函数重载

标签:

原文地址:http://my.oschina.net/donngchao/blog/527497

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!