【问题标题】:C2039 error for string member function .pop_back() and .back()字符串成员函数 .pop_back() 和 .back() 的 C2039 错误
【发布时间】:2013-07-08 23:45:19
【问题描述】:

我正在使用 and 来编写两个在整数和字符串之间互换的函数。第一个函数,string intToStr(int x),使用:

1) std::basic_string::push_back

完美运行。

但是,当第二个函数 int str2Int(const string &str) 使用以下成员函数时,

1) std::basic_string::pop_back
2) std::basic_string::back

我收到以下错误:

1) error C2039: 'back' : is not a member of 'std::basic_string<_Elem,_Traits,_Ax>'  
2) error C2039: 'pop_back' : is not a member of 'std::basic_string<_Elem,_Traits,_Ax>'

完整代码如下:

#include <iostream>
#include <algorithm>
#include <string>

using namespace std;
string intToStr(int x)
{
    bool isNegative;
    int cnt = 0;
    if(x<0)
    {
        isNegative = true;
        x = -x;
    }
    else
    {
        isNegative = false;
    }

    string s;
    while(x)
    {
        s.push_back('0'+x%10);
        x /= 10;
        cnt ++;
        if(cnt%3==0 & x!=0)
            s.push_back(',');
    }


    if(isNegative)
        s.push_back('-');

    reverse(s.begin(),s.end()); //#include <algorithm>

    return s;

}

int str2Int(const string &str)
{
    int result=0, isNegative=0;
    char temp;
    string tempStr = str;
    reverse(tempStr.begin(),tempStr.end());

     // the following code snippet doesn't work??
     // pop_back() and back() are not member function??
    while(!tempStr.empty())
    {
        temp = tempStr.back(); 
        tempStr.pop_back();
        if(temp==',')
            continue;
        else if(temp=='-')
            isNegative = 1;
        else
            result = result*10 + (temp-'0');
    }

    return isNegative? -result:result;
}

【问题讨论】:

  • 有什么问题吗?错误很明显,这些成员函数不存在(在 C++11 之前)对于字符串(请参阅字符串参考 here
  • @Borgleader:再次阅读该参考资料。
  • 很奇怪,push_back() 是合法的成员函数,而pop_back() 不是成员函数。另外,我正在使用 Visual Studio 2008,相当新的 SDK。
  • @DietrichEpp 我重新检查了,back 和 pop_back() 都标记为 C++11。
  • @Borgleader:我没看到括号。

标签: c++ string stl


【解决方案1】:

这些成员函数仅存在于 C++11 中。您必须将代码编译为 C++11 代码才能正确编译。

Visual Studio 2008 附带的编译器不支持 C++11。您将需要使用更新的编译器。

您可以使用 Clang、GCC 或升级到 Visual Studio 2012

【讨论】:

    猜你喜欢
    • 2019-06-20
    • 2017-12-17
    • 2022-11-10
    • 1970-01-01
    • 2019-11-04
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多