/*
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;
}
c++学习-基础-return 语句
最新推荐文章于 2024-04-12 20:32:26 发布