c++学习-基础-函数参数传递-引用形参

001

/*
	Description: 函数参数传递-引用形参
		使用引用形参修改实参
		使用引用形参返回额外信息
		利用const引用避免复制
		更灵活的指向const的引用
			-普通的非const引用形参使用时不太灵活
		传递指向指针的引用 
*/
#include<iostream>
using namespace std;

//  引用形参 
void swap(int &v1,int &v2)
{
	int temp;
	temp = v2;
	v2 = v1;
	v1 = temp;
 } 
 
 void addOne(int x)
 {
 	x = x +1;
 }
 
 void addTwo(int &x)
 {
 	x = x +2;
 }

int main()
{
	int i = 10;
	int j = 20;
	cout<<"before swap():"<<i<<" "<<j<<endl; 
	swap(i,j);
	cout<<"after swap():"<<i<<" "<<j<<endl;
	
	int x = 1,y = 2;
	addOne(x); 
	addTwo(y);
	cout<<x<<" "<<y<<endl;//非引用形参与引用形参的区别 
	return 0;
}

002

#include<iostream>
using namespace std;

void  doOp(int x,int y,int &result1,int &result2,int &result3,int &result4)
{
	result1 = x + y;
	result2 = x - y;
	result3 = x * y;
	result4 = x / y;
}

bool isShorter(const string &s1,const string &s2)
{
	return s1.size()<s2.size(); 
}

string::size_type find_char(const string &s,char c)
{
	string::size_type i = 0;
	while(i != s.size() && s[i] != c)
		++i;
	return i;
}
int main()
{
	int a = 10,b = 2;
	int result1,result2,result3,result4;
	doOp(a,b,result1,result2,result3,result4);
	
	cout<<result1<<" "<<result2<<" "<<result3<<" "<<result4<<endl;
	
	string s1("one");
	string s2("hello");
	
	if(isShorter(s1,s2))
		cout<<"s1短!"<<endl;
	else
		cout<<"s2短!"<<endl;
		
	string s("hello world");
	int result5 = find_char(s,'o');
	cout<<result5<<endl;
		
	return 0;
}

003

#include<iostream>
using namespace std;

//不是交换两个数,是交换指针 
void ptrswap(int *&v1,int *&v2)
{
	int *tmp = v2;
	v2 = v1;
	v1 = tmp;
}
int main()
{
	int i = 10;
	int j = 20;
	int *pi = &i;//交换前:*pi指向i   
	int *pj = &j;//交换前:*pj指向j 
	cout<<i<<","<<j<<endl; 
	cout<<*pi<<","<<*pj<<endl;
	
	ptrswap(pi,pj);//交换两个指针 
	
	cout<<i<<","<<j<<endl;
	cout<<*pi<<","<<*pj<<endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值