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

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




  • 相关阅读:
    obj文件可视化
    TypeError: unsupported operand type(s) for +: 'range' and 'range'
    ubuntu截屏软件shutter
    什么是Redis缓存穿透、缓存雪崩和缓存击穿
    在 ASP.NET Core 5.0 中访问 HttpContext
    如何使用带有BOM的UTF8编码的C#中的GetBytes()?
    ASP.NET Core 5.0 Web API 自动集成Swashbuckle
    ASP.NET Core 5.0 的新增功能
    面试被问到SQL | delete、truncate、drop 有什么区别?
    3个值得学习和练手的.net企业级开源项目,强烈推荐
  • 原文地址:https://www.cnblogs.com/vczf/p/6823263.html
Copyright © 2011-2022 走看看