0

当我尝试调试代码时,它会遇到调试错误“c++ 表达式:字符串下标超出范围”很确定问题是在调用 setCode() 时带来的。如何修复 setCode() 中的代码?

#include <iostream>
#include <stdlib.h>
#include <string>
#include <fstream>
#include <list>
using namespace std;

class test
{
    private:
        string code;
        int digit;

    public:
        //constructor
        test(): code(""), digit(0) { }

        //copy constructor
        test(const test &other):
        digit(other.digit)
        { 
            for(unsigned int i=0; i < code.length(); i++)   
                code[digit] = other.code[digit];
        }

        //set up the private values 
        void setCode(const string &temp, const int num);
        void setDigit(const int &num);

        //return the value of the pointer character 
        const string &getCode() const;
        const unsigned int getDigit() const;
};

const string& test::getCode() const
{
    return code;
}
const unsigned int test::getDigit() const
{
    return digit;
}
void test::setCode(const string &temp, int num) 
{
    code[num] = temp[num];  
}
void test::setDigit(const int &num)
{
    digit = num;
}


int main()
{
    string contents = "dfskr-123";

    test aisbn;
    list<test> simul;
    list<test>::iterator testitr;
    testitr = simul.begin();
    int count = 0;

    cout << contents << '\n';
    aisbn.setCode(contents, count);
    aisbn.setDigit(count);
    simul.push_back(aisbn);
    count++;

    /*for(; testitr !=simul.end(); simul++)
    {
        cout << testitr->getCode() << "\n";
    }*/

}
4

2 回答 2

2

当你创建一个test类的实例时,它里面的字符串是空的。这意味着无论您何时这样做,例如code[something],您都将超出范围。索引是什么并不重要。

您要么需要从一开始就将字符串设置为一定的长度,并确保索引在该范围内。或者通过在需要时动态扩展字符串来确保索引在范围内。

于 2013-04-15T13:30:00.970 回答
1

您必须确保在执行此语句时:

 code[num] = temp[num];  

两者codetemp至少是 size num + 1

于 2013-04-15T13:30:09.033 回答