zoukankan      html  css  js  c++  java
  • “行参为引用”的思考

    1.一个简单程序判断知否含有大写字母

    #include  <iostream>
    using std::cout;	using std::cin; using std::endl;
    
    #include <string>
    using std::string;	
    #include <cstring>
    #include <vector>
    using std::vector;
    
    #include <iterator>
    using std::begin; using std::end;
    
    #include <cstddef>
    using std::size_t; 
    
    #include <cctype>
    
    bool judge_capital( string &s)
    {
    	for(auto c : s)
    	{
    		if(isupper(c))		return true;
    	}
    	return false;
    }
    
    int main()
    {
    	string str = "Hello!";
    	if(judge_capital(str))
    	{
    		cout << "ok" << endl;
    	}else
    	{
    		cout << "no" << endl;
    	}
    
    	return 0;
    	
    }

    初看之下这个程序没有问题,而且运行也正确,可是其中却隐藏了很深的陷阱;

    int main()
    {
    	// string str = "Hello!";
    	if(judge_capital("Hello"))
    	{
    		cout << "ok" << endl;
    	}else
    	{
    		cout << "no" << endl;
    	}
    
    	return 0;
    	
    }

    会报错,无法判断常量字符串是否含有大小写。再看

    int main()
    {
    	auto &str = "Hello";
    	if(judge_capital(str))
    	{
    		cout << "ok" << endl;
    	}else
    	{
    		cout << "no" << endl;
    	}
    
    	return 0;
    	
    }

    常量引用无法赋值给变量引用,所以会报错,因此尽量使用常量引用。

    bool judge_capital( const string &s)
    {
    	for(auto c : s)
    	{
    		if(isupper(c))		return true;
    	}
    	return false;
    }
    
    int main()
    {
    	auto &str = "Hello";
    	if(judge_capital(str))
    	{
    		cout << "ok" << endl;
    	}else
    	{
    		cout << "no" << endl;
    	}
    
    	return 0;
    	
    }

    在只需要读取对象的情况下,改为常量引用可以避免许多的麻烦。

    2.把大写字母改为小写字母。

    #include  <iostream>
    using std::cout;	using std::cin; using std::endl;
    
    #include <string>
    using std::string;	
    #include <cstring>
    #include <vector>
    using std::vector;
    
    #include <iterator>
    using std::begin; using std::end;
    
    #include <cstddef>
    using std::size_t; 
    
    #include <cctype>
    
    bool judge_capital(const string &s)
    {
    	for(auto c : s)
    	{
    		if(isupper(c))		return true;
    	}
    	return false;
    }
    
    void change_lower(string &s)
    {
    	for(auto &c : s)
    	{
    		c = tolower(c);
    	}
    }
    
    int main()
    {
    	string str = "Hollo";
    	change_lower(str);
    	
    	cout << str << endl;
    	return 0;
    	
    }

    在需要修改对象值的时候,使用普通引用。




  • 相关阅读:
    最大化等比例测试演化Demo-传统方法
    Layout-3相关代码:3列布局代码演化三]
    Layout-3相关代码:3列布局代码演化[二]
    Layout-2相关代码:3列布局代码演化[一]
    Layout-1相关代码
    【比赛打分展示双屏管理系统-专业版】Other.ini 配置文件解读以及排行榜界面及专家评语提交展示等具体配置
    Android 开源简单控件
    Android Drawable资源
    Android Service与Thread的区别
    Android事件处理
  • 原文地址:https://www.cnblogs.com/vczf/p/6823263.html
Copyright © 2011-2022 走看看