前言:main函数
在C++中,main函数通常有两种标准的定义方式,分别是:有参数和无参数的main函数
int main() {
// 代码逻辑
return 0;
}
int main(int argc, char *argv[]) {
// 代码逻辑
return 0;
}
你也可以传入第三个三参数,是环境变量,但是一般标准就是两个。
int main(int argc, char *argv[], char *envp[]);
{
return 0;
}
在C++中,函数重载(Function
Overloading)是一种允许在同一个作用域中定义多个同名函数的特性,但这些函数的参数列表(参数类型、数量或顺序)必须不同。函数重载是C++的多态性表现之一,使得同一个函数名可以根据传递的参数执行不同的功能。
1.传入参数数量不同
#include <iostream>
using namespace std;
void display(int a) {
cout << "Display with one parameter: " << a << endl;
}
void display(int a, int b) {
cout << "Display with two parameters: " << a << ", " << b << endl;
}
int main() {
display(5); // 调用 display(int)
display(5, 10); // 调用 display(int, int)
return 0;
}
2.传入参数类型不同
#include <iostream>
using namespace std;
// 重载 print 函数,打印整数
void print(int value) {
cout << "Printing int: " << value << endl;
}
// 重载 print 函数,打印浮点数
void print(double value) {
cout << "Printing double: " << value << endl;
}
// 重载 print 函数,打印字符串
void print(const string &value) {
cout << "Printing string: " << value << endl;
}
int main() {
print(10); // 调用 print(int)
print(3.14); // 调用 print(double)
print("Hello"); // 调用 print(const string &)
return 0;
}
3.传入参数类型顺序不同
#include <iostream>
using namespace std;
void process(int a, double b) {
cout << "Process with (int, double): " << a << ", " << b << endl;
}
void process(double a, int b) {
cout << "Process with (double, int): " << a << ", " << b << endl;
}
int main() {
process(5, 3.14); // 调用 process(int, double)
process(3.14, 5); // 调用 process(double, int)
return 0;
}
出现的问题如下
如果,你的函数重载有了默认值,就会出现问题!!但是有时候我们就必须要求在函数中设定默认值??该如何解决??
使用函数指针!
#include <iostream>
using namespace std;
// 重载的两个 test 函数
int test(int a) {
return a;
}
int test(int a, double b) {
return a + b;
}
int main() {
// 定义函数指针,明确指定要调用的重载版本
int (*testInt)(int) = test; // 指向 test(int)
int (*testIntDouble)(int, double) = test; // 指向 test(int, double)
// 使用函数指针调用具体的重载函数
cout << "Calling test(int): " << testInt(10) << endl;
cout << "Calling test(int, double): " << testIntDouble(10, 2.5) << endl;
return 0;
}
函数指针和指针函数
#include <iostream>
using namespace std;
int MaxValue(int x, int y)
{
return (x > y) ? x : y;
}
int MinValue(int x, int y)
{
return (x < y) ? x : y;
}
int Add(int x, int y)
{
return x + y;
}
bool ProcessNum(int x, int y, int(*p)(int a, int b)) //回调函数--《超强
{
cout << p(x, y) << endl;
return true;
}
int main()
{
int x = 10, y = 20;
cout << ProcessNum(x, y, MaxValue) << endl;
cout << ProcessNum(x, y, MinValue) << endl;
cout << ProcessNum(x, y, Add) << endl;
return 0;
}