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;
    }

  • 相关阅读:
    jdk9 特性
    jdk8 特性
    Eclipse中Spring插件的安装
    C++避免程序运行完后窗口一闪而过的方法
    完全二叉树节点个数
    Shell 编写倒着的*三角形
    Drools源于规则引擎
    Spring Data MongoDB 三:基本文档查询(Query、BasicQuery
    docker环境搭建
    MyBatis根据数组、集合查询
  • 原文地址:https://www.cnblogs.com/mxw09/p/1863058.html
Copyright © 2011-2022 走看看