C++默认参数和函数重载的学习

默认参数

默认参数是指当函数调用中省略实参时自动使用的一个值。

#include <iostream>
using std::cout;
using std::endl;

// 声明
char *return_n_str(const char *str, int n = 1);     // 1为默认参数

int main()
{
    // 调用
    const char *str = "hello world";
    cout << str << endl;
    char * str_1 = return_n_str(str);  // 使用默认参数1,将返回第一个字符
    cout << str_1 << endl;
    delete [] str_1;       // 释放内存
    str_1 = nullptr;

    char *str_4 = return_n_str(str, 4);
    cout <<  str_4 << endl;   // 不使用默认参数,将返回前2个字符
    delete [] str_4;        // 释放内存
    str_4 = nullptr;
    return 0;
}

// 定义
char *return_n_str(const char *str, int n)  // 定义时不能加默认参数
{
	if(n < 0)
	{
		n = 0;
	}
	char *p = new char[n+1];
	int i;
	for(i = 0; i < n && str[i]; i++)
	{
		p[i] = str[i];
	}
	while(i <= n)
	{
		p[i++] = '\0';
	}
	return p;
}

注意

  • 对于带参数列表的函数,必须从右向左添加默认值。
  • 调用时,实参按从左到右的顺序依次被赋给相应的形参。
int func_a(int x, int y = 4, int z = 5);     // 正确
int func_b(int x, int y = 6, int z);         // 错误
int func_c(int x = 1, int y = 2, int z = 3); // 正确

// 调用时,实参按
func_c(2);      // 同 func_c(2, 2, 3);
func_c(6,7);    // 同 func_c(6, 7, 3);
func_c();       // 同 func_c(1,2,3);

函数重载

函数重载是指可以有多个同名的函数。

函数重载的关键时函数的参数列表。重载的唯一条件是函数的参数列表不同。比如,参数个数,参数类型不同。

#include <iostream>

using std::cout;
using std::endl;

void func(const char *str);     // #1
void func(char *str);           // #2
void func(int i);               // #3
void func(long i);              // #4
void func(double i);            // #5
void func(double &i);           // #6
int main()
{
    const char *str1 = "Hyunqi";
    char str2[20] = "hello world";
    func(str1);         // 调用 #1
    func(str2);         // 调用 #2
    func(2023);         // 调用 #3
    func(2023L);        // 调用 #4
    func(2023.0);       // 调用 #5,因为是右值
    double i = 2022.0;
    // func(i);            // 报错,因为类型引用和类型本身视为相同参数
    return 0;
}

void func(const char *str)
{
    cout << "This is #1" << endl; 
    cout << str << endl;
}
void func(char *str)
{
    cout << "This is #2" << endl;
    cout << str << endl;
}
void func(int i)
{
    cout << "This is #3" << endl;
    cout << "int: " << i << endl;
}
void func(long i)
{
    cout << "This is #4" << endl;
    cout << "long: " << i << endl;
}
void func(double i)
{
    cout << "This is #5" << endl;
    cout << "double: " << i << endl;
}
void func(double &i)
{
    cout << "This is #6" << endl;
    cout << "double&: " << i << endl;
}

注意

  • 编译器在检查函数参数列表时,将把类型引用和类型本身视为相同参数。
  • 函数重载区分const和非const
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值