首页 > 编程语言 > 详细

c++——引用的使用

时间:2019-03-19 23:29:56      阅读:182      评论:0      收藏:0      [点我收藏+]

1、使用引用避免拷贝

c++中拷贝大的类类型对象或容器对象比较低效,甚至有的类型不支持拷贝,这种情况下只能通过引用形参访问该类型的对象

当函数无需修改引用形参的值时,最好使用常量引用

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 using std::string;
 5 
 6 const string &shorterString(const string &s1, const string &s2) {
 7     return s1.size() <= s2.size() ? s1 : s2;
 8 }
 9 int main() {
10     string s1 = "hello";
11     string s2 = "hi";
12     string s = shorterString(s1,s2);
13     cout << s << endl;
14 }

结果:hi

2、函数返回多个值

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 using std::string;
 5 
 6 string::size_type find_char(const string &s, char c,
 7     string::size_type &occurs) {
 8     auto ret = s.size();
 9     occurs = 0;
10     for (decltype(ret) i = 0; i != s.size(); ++i) {
11         if (s[i] == c) {
12             if (ret == s.size())
13                 ret = i;
14             ++occurs;
15         }
16     }
17     return ret;
18 }
19 
20 int main() {
21     string s = "helloo";
22     string::size_type ctr;
23     auto index = find_char(s, o, ctr);
24     cout << ctr << endl;
25 }

输出:2

 

参考:

《c++ primer》(第五版)

 

c++——引用的使用

原文:https://www.cnblogs.com/cxc1357/p/10561533.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!