Chinaunix首页 | 论坛 | 博客
  • 博客访问: 88266
  • 博文数量: 60
  • 博客积分: 4002
  • 博客等级: 中校
  • 技术积分: 645
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-17 18:11
文章分类

全部博文(60)

文章存档

2011年(60)

我的朋友

分类: C/C++

2011-03-30 22:25:55


Function overloading is the practice of declaring the same function with different signatures. The same function name will be used with different number of parameters and parameters of different type. But overloading of functions with different return types are not allowed.

For example in this C++ Tutorial let us assume an AddAndDisplay function with different types of parameters.

//C++ Tutorial - Sample code for function overloading
    void AddAndDisplay(int x, int y)
    {
       cout<<" C++ Tutorial - Integer result: "<<(x+y);
    }

    void AddAndDisplay(double x, double y)
    {
       cout<< " C++ Tutorial - Double result: "<<(x+y);
    }

    void AddAndDisplay(float x, float y)
    {
       cout<< " C++ Tutorial - float result: "<<(x+y);

    }


Some times when these overloaded functions are called, they might cause ambiguity errors. This is because the compiler may not be able to decide what signature function should be called.

If the data is type cast properly, then these errors will be resolved easily. Typically, function overloading is used wherever a different type of data is to be dealt with. For example this can be used for a function which converts farenheit to celsius and vice versa. One of the functions can deal with the integer data, other can deal float for precision etc.,

阅读(260) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~