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;
    	
    }

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




  • 相关阅读:
    pycharm突然变成了一个tab变成两个空格,查询无果
    79--JT项目17(Dubbo框架入门)
    79--JT项目17(SOA/RPC思想/zookeeper集群搭建)
    Java instanceof Operator
    12.21.4命名为Windows
    12.20.1汇总功能说明
    第24章分区
    Laravel 中间件的使用
    Laravel session的使用
    Laravel 数据分页
  • 原文地址:https://www.cnblogs.com/vczf/p/6823263.html
Copyright © 2011-2022 走看看