函数非引用形参

函数非引用形参

知识导图

一,不同形参的区别

#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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值