重载

重载

  --同一作用域中,函数名相同,参数表不同的函数

  -- 只有同一作用域中的同名函数才涉及重载问题,不同作用域中同名函数遵循标识符隐藏原则

重载解析

  --完全匹配 > 常量转换 > 升级转换 > 标准转换 > 自定义转换 > 省略号匹配

函数指针的类型决定其匹配的重载版本

#include<iostream>
using namespace std;
//重载--参数个数差异、参数类型差异

//有效重载

void foo()
    {
        cout << "foo(1)" << endl;
    }

void foo( int a )
    {
        cout << "foo(2)" << endl;
    }

void foo(int a, int b)
    {
        cout << "foo(3)" << endl;     
    }

void foo(int a, float b)
    {
        cout << "foo(6)" << endl;
    }
void foo (float a, int b)
    {
        cout << "foo(7)" << endl;
    }

//无效重载


/*
出错。同一作用域,参数个数相同,参数类型相同
void foo(int b, int a)
    {
    
        cout << "foo(4)" << endl;
    }

出错。重载与返回值无关,只看参数
int foo(int a , int b)
    {
        cout << "foo(5)" << endl;
    }
    */

//重载匹配顺序---安全、最小工作量原则

void bar ( char *p, int n)//需要类型升级 char-->int
    {
        cout << "bar(1)" << endl;
    }
void bar ( const char *p, char c)//仅需常量转换char*-->const char *
    {
        cout << "bar(2)" << endl;
    }

//////////////////////////

void fun(char c)//需要标准转换 short-->char,信息丢失
    {
        cout << "fun(1)" << endl;
    }

void fun(int c)//升级转换 short ->int ,信息完整
    {
        cout << "fun(2)" << endl;
    }
void fun (long ll)//过分的升级short->long 
    {
        cout << "fun(3)" << endl;
    }

int main()
    {
        foo();
        foo(10);
        foo(10,20);
        foo(10,1.23f);//不写f,是double类型,函数没有可匹配,重载歧义。
        foo(1.23f,10);
        //////////////////
        char *p,c;
        bar(p,c);//常量转换高于版本转换
        /////////////////////
        short s;
        fun(s);//安全的前提下,保证做的工作最少
        return 0;
    }

名字空间与重载
#include<iostream>
using namespace std;

namespace ns1
    {
        void foo(int a)
            {
                cout << "ns1::foo(1)" << endl;
            }
    };

namespace ns2
    {
        void foo(double b)
            {
                cout << "ns2::foo(2)" <<endl;
            
            }

    };

int main ()
    {
        using namespace ns1;
        using namespace ns2;
     //    虽不在同一作用域,可是却在同一作用域可见,重载
        foo(2);
        foo(1.23);

        using ns1::foo;
        //ns1的foo被引入当前作用域,隐藏了ns2中的foo,不构成重载
        foo(2);
        foo(1.23);

        using ns2::foo;
        //ns1/ns2中的foo都在当前作用域中,构成重载
        foo(2);
        foo(1.23);
        
        return 0;}

 

 

 

posted @ 2016-01-05 16:22  amberblue  阅读(153)  评论(0编辑  收藏  举报