2011-02-15 89 views
4

我有一个函数,它需要const字符串&值作为参数。 我想获得这个字符串的值,以便我可以在函数中操作它。所以,我想存储的数值为串returnVal但这不起作用:如何获得const string&的值在C++

string returnVal = *value

回答

6

根本就

string returnVal = value; 

由于值不是一个指针,但你并不需要参考指针解除引用操作符(否则它将是const字符串*值)。

2
string returnVal = value; 

值不是一个需要解引用的指针,它是一个引用,语法与处理普通旧值相同。

0

为什么不创建一个局部变量,像这样:

void foo(const std::string &value) 
{ 
    string returnVal(value); 

    // Do something with returnVal 

    return returnVal; 
} 
1

既然你打算无论如何要修改字符串,为什么不按值传递呢?

void foo(std::string s) 
{ 
    // Now you can read from s and write to s in any way you want. 
    // The client will not notice since you are working with an independent copy. 
}