函数非引用形参
知识导图
一,不同形参的区别
#include<iostream>
using namespace std;
void AddOne(int x) //非引用,只是拷贝a的值,不修改原值
{
x = x + 1;
}
void AddTwo(int *x) //非引用,只是拷贝a的地址,修改原值
{
*x = *x + 2;
}
void AddThree(int &x) //引用,修改原值
{
x = x + 3;
}
int main()
{
int a,b,c;
a = 1;
b = 2;
c = 3;
cout << "加之前" << a <<endl;
AddOne(a);
cout << "加之后" << a <<endl;
cout << endl;
cout << "加之前" << b <<endl;
AddTwo(&b);
cout << "加之后" << b <<endl;
cout << endl;
cout << "加之前" << c <<endl;
AddThree(c);
cout << "加之后" << c <<endl;
cout << endl;
return 0;
}
二,const形参与非const形参(非指针类型)
#include<iostream>
using namespace std;
int add(int x,int y)
{
return x + y;
}
int add_2(const int x,const int y)
{
return x + y;
}
int main()
{
int a,b;
a = 1;
b = 2;
const int c = 2;
const int d = 4;
cout << add(a,b) << endl;
cout << add_2(a,b) << endl;
cout << add(c,d) << endl;
cout << add_2(a,b) << endl;
return 0;
}
可以看出const与非const实参与形参传输很灵活,但是有一点,不能修改const的值。
int add_2(const int x,const int y)
{
return x++;
}
三,const形参与非const形参(指针类型)
1,很重要的一点是,无论const什么类型都不能修改其值。
#include<iostream>
using namespace std;
int Add(int *ip)
{
return *ip + 1;
}
int Add_2(const int *ip)
{
return *ip + 2;
}
int main()
{
int a;
a = 2;
const int b = 4;
cout << Add(&a) << endl;
cout << Add_2(&b) << endl;
cout << Add_2(&a) << endl;
return 0;
}
2,在指针形参中可以 const--->const、非const--->非const,非const--->const,但是不能const--->非const
四,函数重载
同一个函数名,只要形参不一样,可以共存在一个程序中。
#include<iostream>
using namespace std;
void abc(int a)
{
}
void abc(double)
{
}
int main()
{
return 0;
}
但是如果像下面这样,有abc(const int a),虽然和其他函数形参不一样,但是C++报错,因为C++兼容C,在C语言中,下面的格式是错误的,所以,切记。
#include<iostream>
using namespace std;
void abc(int a)
{
}
void abc(const int a)
{
}
void abc(double)
{
}
int main()
{
return 0;
}