C++相对C的一个优势就是它允许开发者使用引用参数以取代对象指针。引用相对于指针的主要优点是易于使用,你可以从下面的代码中看出这一点:
//使用指针 const Employee * pFirst = &( aEmployees[ 0]); std::cout << pFirst->GetUserName(); //使用引用 const Employee & First = aEmployees[ 0]; std::cout << First.GetUserName();
有些时候,你用引用的另一个优势就是初始化引用参数时你不能让它指向一个不可能存在的地方。尽管你可以用指针达到同样的效果,不过你很快就会发现那样做显得比较麻烦:
const Employee * const p = aEmployees[ 0];
向函数传递引用参数而不是指针的其它优势如下:
下面是使用引用类型的函数原型的例子:
void AdjustIllegalCharactersFromFileName( string_type & strFileName); void ApplicationTrace( const string_type & strMessage); inline bool case_insensitive_compare( const string_type & strFirst, const string_type & strSecond); string_type ComExceptionToString( const _com_error & exc); void LogException( ostream_type & streamOut, const string_type & strContext); void DivideUrlInSiteAndLinkWithinSite( const string_type & strURL, string_type & strSite, string_type & strLinkWithinSite); HRESULT CreateShortcut( const string_type & strPathObj, const string_type & strPathLinkObj, const string_type & strDescObj, const string_type & strArgumentsObj); void FillNewDictionariesCollection( NewDictionariesCollection & collNewDictionaries); long GetWordsSum( long nSumSoFar, WordTranslationsCollection::value_type & CurrentWord); HKEY StringToRootKey( const string_type & strDirectory);