C++学习(五)—函数(二)

函数重载

#include<iostream>

using namespace std;

// 函数重载  

//	满足函数重载条件
//	1、作用域必须相同
//	

/*class Teacher
{
	void f() {};	成员函数,不能作为重载的条件
};*/


//	2、函数名称要相同
//	3、函数参数类型不同或者个数不同或着顺序不同


void f()
{
	cout << "调用函数 f()" << endl;
}

void f(int a)
{
	cout << "调用函数 f(int a)" << endl;
}

void f(double a)
{
	cout << "调用函数 f(double a)" << endl;
}

/*
int f(double a)
{
	cout << "调用函数 f(double a)" << endl;
}
*/

//	函数返回值是否能作为函数重载的条件?返回值不可以作为函数重载的条件,原因会出现二义性

//	引用的重载版本
//	对于引用而言,加const 和不加 const 也可以作为重载的条件

void f1(int a)
{
	cout << "调用 f1(int a)" << endl;
}

void f1(int &a)		//	int &a = 10;
{
	cout << "调用 f1(int &a)" << endl;
}

void f1(const int &a)	//	const int &a = 10;
{
	cout << "调用 f1(const int &a)" << endl;
}


//	函数重载遇到函数的默认参数

void f3(int a,int b = 10)
{
	cout << "调用 f3(int a,int b)" << endl;
}

void f3(int a)
{
	cout << "调用 f3(int a)" << endl;
}


void test01()
{
	f(1);
}

void test02()
{
	int a = 10;
	//	f1(a);
	//	f1(10);
}

void test03()
{
	//f3(10);  //注意避免二义性
}

int main()
{
	//	test01();
	//	test02();
	test03();
	system("pause");
	return 0;
}

函数重载原理

编译器在底层会将函数名做二次修饰方便内部访问函数体

extern C

在C++下可以运行C语言文件

#include<iostream>

using namespace std;

#include "test.h"
//	extern "C" void show();  //	告诉编译器,不要用C++的方式去链接,要用C语言的方式链接

void test01()
{
	show();
}

int main()
{
	test01();
	system("pause");
	return 0;
}
test.c
#pragma once


//  如果是C++在运行本文件的时候,extern包含的内容用C语言链接
#ifdef __cplusplus 
extern "C" {
#endif // __cplusplus 



#include<stdio.h>

	void show();

#ifdef __cplusplus 
}
#endif // __cplusplus 

test.c
#include "test.h"

void show()
{
	printf("hello,world!\n");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

walkerrev_ll

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值