“行参为引用”的思考

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

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




 

posted @ 2016-01-15 16:38  Vzf  阅读(247)  评论(0编辑  收藏  举报