将字符串文字传递给需要字符串的函数

问题描述 投票:0回答:1

让我们假设我有一个函数,期望参数为字符串(非const)。但是,正如我们所知,字符串文字本质上是const。有什么办法可以将字符串文字传递给期望非常量的函数。我知道这会导致错误,因为字面量本质上是const,但是函数期望非const。任何强制转换该功能的方法都可以使用。听说有const_cast。我可以使用它吗?

   void str(string &s); // my function which is expecting a non const string
   // main . i want to do something like this 
   str("Blah"); // error
c++ string function const
1个回答
0
投票

绝对好。 std :: string的ctor看起来像:

string(const char* text);

因此,对str("Blah")的调用将创建一个临时字符串对象(通过调用上述ctor),然后将调用str方法。

© www.soinside.com 2019 - 2024. All rights reserved.