C++技术——默认参数

1 默认参数特点:

(1)声明和定义的形式不一样:默认参数在函数声明的时候写, 定义的时候不需要写。

(2)如果引用使用默认参数,则默认参数的值必须全局变量的值,因为默认参数的值需要在函数声明时就指定,只能通过全局变量的值来引用,不可通过函数传值来赋值,那样的话表示是调用的时候才赋值,这不符合默认参数的定义。

#include <iostream>
using namespace std;

int ar=10;

void show(int &a, int &b=ar)
{
	cout<<"(a,b)"<<a<<","<<b<<endl;
}

(3)当函数重载与默认参数同时出现时,像下面的例子就存在歧义,们把两者合为一体。

#include <iostream>  
using namespace std;  
  
//默认函数
void DefaultArguTest(int arg1 = 1, int arg2 = 2, int arg3 = 3)
{  
    cout<<arg1<<" "<<arg2<<" "<<arg3<<endl;  
}

//重载  
void DefaultArguTest()
{
    cout<<"DefaultArguTest"<<endl;
} 
  
int main(void)  
{  
    //不给参数  
    DefaultArguTest();  
  
    system("pause");  
    return 0;  
}  
  

(4)复写函数时不要更改默认参数。

#include <iostream>  
#include <string>  
using namespace std;  
  
class Base  
{  
public:  
    virtual void Print(int i = 1, int j = 2)  
    {  
        cout<<"In base: "<<i<<" "<<j<<endl;  
    }  
};  
  
class Child : public Base  
{  
public:  
    //手动的将默认参数修改了。
    void Print(int i = 3, int j  = 4 )  
    {  
        cout<<"In Child: "<<i<<" "<<j<<endl;  
    }  
};  

int main(void)  
{  
    //静态绑定  
    cout<<"Static bind:"<<endl;  
    Child* child = new Child();  
    child->Print();  
  
    //动态绑定  
    cout<<"Dynamic bind:"<<endl;  
    Base* base = new Child();  
    base->Print();  
      
  
    system("pause");  
    return 0;  
}  

结果:
Static bind:
In Child: 3 4
Dynamic bind:
In Child: 1 2 //理论上错的,应该是:In Child: 3 4 
因为为了效率,函数的默认参数是使用静态绑定的,换句话说,
不管你有没有多态,我只关心你用什么指针来调,基类指针就调
用基类的默认参数,子类指针就给出子类的默认参数。而不像我们
多态那样,会发生动态绑定,可以用基类指针调用子类函数。而我们
在一个动态绑定的函数中使用了静态绑定的参数,结果肯定是不对的!


猜你喜欢

转载自blog.csdn.net/wghkemo123/article/details/82664390
今日推荐