c++ - 错误 : passing ‘const string {aka const std::__cxx11::basic_string<char>}’ as ‘this’ argument

标签 c++ string c++11 double

我有以下处理 double 的代码:

static bool
double_param(const char ** p, double * ptr_val)
{
    char *end;
    errno = 0;
    double v = strtod(*p, &end);
    if (*p == end || errno) return false;
    *p = end;
    *ptr_val = v;
    return true;
}

此代码用于检查传递的双参数是否无效,如下所示:

if (!double_param(&p, &b1)) //p is pointer and b1 is parameter.
        //throw error;

而且,我需要编写一个等效代码来处理 3 个字符长的字符串。我自己得到了这个:

static bool
string_param(const char ** p, const string * ptr_val)
{
    char *end;
    errno = 0;
    int v = strtol(*p, &end, 10);
    if (*p == end || errno) return false;
    *p = end;
    *ptr_val = v;
    return true;
}

但我得到以下编译错误:

error: passing ‘const string {aka const std::__cxx11::basic_string<char>}’ as ‘this’ argument discards qualifiers [-fpermissive]
 (*ptr_val) = v;
            ^

感谢任何解决此错误的建议。另外,请指出我代码中的错误并稍微解释一下,以便我更好地理解和学习。提前致谢。

最佳答案

*ptr_val 是指向 const string 的指针。您正在尝试更改 const string 的值,当然您不能这样做。

你可以像这样做一个常量指针:string * const ptr_val

这意味着您可以更改指针指向的数据的值,但不能更改指针指向的内容。

关于c++ - 错误 : passing ‘const string {aka const std::__cxx11::basic_string<char>}’ as ‘this’ argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38743746/

相关文章:

c++ - Visual Studio 'non-standard syntax; use ' &' to create a pointer to member'

c++ - VC++ 2010 错误 LNK2019 : unresolved external symbol

c++ - 非局部非内联变量的初始化 : does it take place strictly before the `main()` function call?

python - 有效地从字符串末尾弹出子字符串

c++ - 明智地填充 texture3d 切片

string - python 3.x 中 stdin.write() 的格式化字符串

我可以只释放字符串的一部分吗?

c++ - 为什么 C++ 异步在没有 future 的情况下按顺序运行?

c++ - GNU g++ 4.9.2 中的重载 endl 编译问题

c++ - 如何在不调用复制构造函数的情况下向 vector 添加元素?