函数重载
#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");
}