Sté*_*ane 9 c++ recursion signature
给定这两个修改并返回字符串的函数:
// modify the original string, and for convenience return a reference to it
std::string &modify( std::string &str )
{
// ...do something here to modify the string...
return str;
}
// make a copy of the string before modifying it
std::string modify( const std::string &str )
{
std::string s( str );
return modify( s ); // could this not call the "const" version again?
}
Run Code Online (Sandbox Code Playgroud)
这段代码适用于我使用GCC g ++,但我不明白为什么/如何.我担心第二个函数会调用自己,让我失控,直到堆栈耗尽为止.这保证有效吗?
你有两个重载函数:
std::string &modify( std::string &str )
std::string modify( const std::string &str )
Run Code Online (Sandbox Code Playgroud)
你通过的是非常规合格的std::string.因此,采用非const限定参数的函数更适合.如果不存在,编译器可以将非const限定字符串转换为const限定字符串以进行调用,但是对于函数重载,不需要转换的调用比需要转换的调用更合适.