zoukankan      html  css  js  c++  java
  • C++之函数重载

    重载函数

    (1)定义:将一组功能非常相近的函数定义为重载函数。

    (2)一组重载函数是以参数类型或参数个数加以区别的,只有返回值不同不是一组重载函数,将会产生编译错误。

    (3)编译器调用重载函数的规

    #include <stdio.h>

    void ShowMessage(const char* Text,int Type);
    void ShowMessage(const char* Text,unsigned int Type);

    int main()
    {
    unsigned char i=0;
    ShowMessage("hello",i);
    return 0;
    }

    void ShowMessage(const char* Text,int Type)
    {
    printf("Text=%s,Type=%d\n",Text,Type+1);
    }
    void ShowMessage(const char* Text,unsigned int Type)
    {
    printf("Text=%s,Type=%d\n",Text,Type);
    }

    输出结果:Text=hello,Type=1

    因为对参数个数相同的重载进行调用时,编译器依次使用下面的规则将实参与形参进行匹配,确实重载函数的调用。

    (1)具有与实参类型相同的形参的重载函数

    (2)转换实参,将T转换成T&,或T&转换为T,或T转换为const T,然后寻找形参类型匹配的重载函数(T为某数据类型)

    (3)实参进行标准的类型转换,如char→int→unsigned int,然后寻找形参类型匹配的重载函数

    (4)使用构造函数的转换实参,使其与某一重载函数匹配。例如,如果类A有构造函数A(int),那么int型转换函数进行转换,使其一重载函数匹配

    (5)使用类型转换函数进行转换,使其与某一重载函数匹配

    显然,上述例子符合第3种情况。

    再看下面例子:

    #include <stdio.h>

    void ShowMessage(const char* Text,const char* Caption);
    void ShowMessage(const char* Text,unsigned int Type);

    int main()
    {
    ShowMessage("hello",NULL); //NULL==0
    return 0;
    }

    void ShowMessage(const char* Text,const char* Caption)
    {
    printf("Text=%s,Type=%s\n",Text,Caption);
    }
    void ShowMessage(const char* Text,unsigned int Type)
    {
    printf("Text=%s,Type=%d\n",Text,Type);
    }

    结果:会产生编译错误 error C2668: 'ShowMessage' : ambiguous call to overloaded function

    因为编译器无法判断第二个参数是空字符串NULL,还是整数0。所以,重载函数的定义和调用会涉及类型转换的细节问题,在设计时要考虑全面。

  • 相关阅读:
    解决:hdfs: org.apache.hadoop.security.AccessControlException(Permission denied)
    新的开始
    死锁问题------------------------INSERT ... ON DUPLICATE KEY UPDATE*(转)
    hql- 使用like的小坑①
    数美面试检讨
    问题:计算foldRight(1)(_-_) 与foldLeft(1)(_-_)值不一样
    学习笔记之流文件操作01(拷贝文件)
    学习笔记之正则表达式
    数据结构之单链表
    (转)消息中间件(二)MQ使用场景
  • 原文地址:https://www.cnblogs.com/danshui/p/2345045.html
Copyright © 2011-2022 走看看