簡體   English   中英

字符串成員函數.pop_back()和.back()的C2039錯誤

[英]C2039 error for string member function .pop_back() and .back()

我正在使用和編程兩個在整數和字符串之間交換的函數。 第一個函數,字符串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中。 您必須將代碼編譯為C ++ 11代碼才能正確編譯。

Visual Studio 2008附帶的編譯器不支持C ++ 11。 您將需要使用更新的編譯器。

您可以使用Clang,GCC或升級到Visual Studio 2012

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM