neu*_*cer 1 c++ g++ reference function char
如果我声明一个这样的函数:
string hash (char* key)
Run Code Online (Sandbox Code Playgroud)
那么我对key所做的任何改变也会在函数退出时改变它的值,对吗?
我想在函数中复制它,以便我可以安全地更改它而不更改原始值.
我试过这个,但它不起作用.
char temp = key;
Run Code Online (Sandbox Code Playgroud)
怎么做到呢?
可能最明显的是将参数更改为字符串:
std::string hash(std::string key) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
在典型情况下,您希望它是a std::string const &,但在这种情况下,您需要原始的可修改副本,因此您可以按值传递字符串.由于字符串可以(隐式)从a构造char *,您仍然可以将指针传递给char而没有问题(并且编译器将在需要时自动构造字符串).