C++中函数的默认参数

来源:互联网 发布:matlab2014 for mac 编辑:程序博客网 时间:2024/05/05 19:07

一、在C++中我们可以为函数指定默认的参数

(1)、典型的例子,一个参数

#include<iostream>
using namespace std;
void test(int x=12)
{
cout<<x<<endl;
}
void main()
{
test();
test(15);
}

运行的结果如下:


在函数中提供了默认的参数,我们就可以在调用函数的时候不提供参数。

(2)、函数带有两个参数

#include<iostream>
using namespace std;
void test(int x=12,int y=19)
{
cout<<x<<"\t"<<y<<endl;
}
void main()
{
test();
test(15);
}

函数中提供了默认的参数,可以提供一个参数,或不提供参数也可以。

二、在C++中如果有个在重载的时候有不带参数的函数就会出错

#include<iostream>
using namespace std;
void test(int x=12)
{
cout<<x<<endl;
}
void test()
{
}
void main()
{
test();
test(15);
}

这种方式的就会报错。

三、在类中也是相同的情况

#include<iostream>
using namespace std;
class A
{
public:
    void test(int x=12){cout<<x<<endl;}
};
void main()
{
A a;
a.test();
a.test(13);
}


四、类的构造函数提供默认值

1、我们可以为一个类的构造函数为成员变量提供初值

#include<iostream>
using namespace std;
class A
{
public:
A():x(5),y(7){cout<<x<<"\t"<<y<<endl;}
private:
const int x,y;
};
void main()
{
A a;
}


2、使用该方式可以进行对常量进行初始化

#include<iostream>
using namespace std;
class A
{
public:
A(int i,int j):x(i),y(j){cout<<x<<"\t"<<y<<endl;}
private:
const int x,y;
};
void main()
{
A a(4,5);
}

原创粉丝点击