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

    // strtref.cpp -- using structure references
    #include <iostream>
    using namespace std;

    void Fun(const int *num)
    {
        //num=435;
        cout<< *num<<",const fun"<<endl;
    }

    void Fun(int *num)
    {
        //num=435;
        cout<< *num<<",not const fun"<<endl;
    }
    int main()
    {
        const int num=999;

        const    int *p=&num;

      int avg=123;

        int *p2=&avg;

     //因为Fun的参数是指针类型,所以能根据const和非const来重载,如果void Fun(int num) 和 void Fun(const int num)就不能重载
        Fun(p);//输出 “999,const fun”
        Fun(p2);//输出 “123,not const fun”
        return 0;

    }

    但是注意,非const实参也能匹配const形参,但是const实参不能匹配非const形参:
    1.非const实参也能匹配const形参

    #include <iostream>
    using namespace std;

    void Fun(const int *num)
    {
        //num=435;
        cout<< *num<<",const fun"<<endl;
    }

    int main()
    {
        int avg=123;
        int *p2=&avg;
        
        Fun(p2);//输出“123,const fun”
        return 0;
    }


    2.const实参不能匹配非const形参 ,下面这段代码编译不能通过,会报错“不能讲const int * 转换为 int*”
    #include <iostream>
    using namespace std;

    void Fun( int *num)
    {
        //num=435;
        cout<< *num<<",const fun"<<endl;
    }

    int main()
    {
        int avg=123;
        const int *p2=&avg;
        
        Fun(p2);
        return 0;
    }

  • 相关阅读:
    Mybatis中的设计模式
    Mybatis的#{}和${}的区别是什么?
    ES的写入速度优化
    康师傅JVM:垃圾回收相关概念(十六)
    i++为什么不是原子操作?
    Zookeeper的watch机制
    LeetCode 1.两数之和
    ESP 8266 引脚图
    Arduino 将 String 转化为 int
    微擎修改 icon.jpg 后项目主页未变
  • 原文地址:https://www.cnblogs.com/mxw09/p/1863058.html
Copyright © 2011-2022 走看看