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

  • 相关阅读:
    3.25Java常量
    3.26Java逻辑运算符
    3.26Java关系运算符
    Java标识符
    3.27Java位运算符
    3.26Java运算符(operator)
    3.26Java字符型(char)变量、常量
    3.26Java布尔类型(boolean)变量、常量
    《算法导论》第9章 顺序统计学 (1)最小值和最大值
    《算法导论》第8章 线性时间排序 (1)计数排序
  • 原文地址:https://www.cnblogs.com/mxw09/p/1863058.html
Copyright © 2011-2022 走看看