c++学习-基础-return 语句

/*
	Description: return 语句
	两种形式:
		return;
		return 返回值;
	具有返回值的函数:
		1.主函数main的返回值
		2.返回非引用类型
		3.返回引用
		4.千万不要返回局部对象的引用
		5.引用返回右值
		6.千万不要返回指向局部对象的指针 
*/
#include<iostream>
using namespace std;

void do_a()
{
	cout<<"nothing matters when you are dancing"<<endl;
	return ;//提前结束 
	cout<<"nothing matters when you are dancing"<<endl;
}

void swap(int &v1,int &v2)
{
	if(v1==v2)
		return;
	int tmp = v2;
	v2 = v1;
	v1 = tmp;
} 
 
 int add(const int &a,const int &b)
 {
	int sum = a + b;
	return sum; 	
 }
 
 int& add_one(int &x)
{
	++x;
	return x;//返回的是x自身 
}

string make_plural(size_t ctr,const string &word,const string &ending)
{
	return (ctr==1) ? word : word + ending;
}

const string& shorter_string(const string &s1,const string &s2)
{
	return s1.size() < s2.size() ? s1 : s2;
}

const string & manip(const string& s)
{
	string ret = s;
	return ret;//返回的是ret,但是ret是一个局部对象   不可以这么写 
}

int* manip2()
{
	int a = 100;
	int *p = &a; 
	return p;//不可以这么写 
} 
 
char &get_val(string &str,string::size_type ix)
{
 	return str[ix];
} 

int main()
{
	do_a();
	
	int a = 1,b = 10;
	swap(a,b);
	cout<<a<<" "<<b<<endl;

	
	int a2 = 1;
	int &b2 = add_one(a2);
	++b2;
	cout<<a2<<" "<<b2<<endl;
	
	int cnt = 6;
	string result = make_plural(cnt,"dog","s");
	cout<<result<<endl;
	
	cout<<shorter_string("hello","dog")<<endl;
	
	string s("hello");
	char &c = get_val(s,1);
	c = 'i';
	cout<<s<<endl;
	
	get_val(s,0) = 'k';
	cout<<s<<endl;
	
	return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值