c ++引用参数未更新

时间:2012-10-28 18:00:55

标签: c++

我正在尝试编写一个简单的函数来从字符串中的表达式中提取下一个数字,我的问题是函数退出后引用参数ioIsValidExpression没有被更新。看起来我实际上引用了正确的变量(而不是临时变量),因为test3的地址(在调用getNextNumber(...)之前调用它)和ioIsValidExpression(函数内部的名称)是相同的。< / p>

我希望这在某个地方是一个令人尴尬的错误,但是我无处可去试图弄清楚这一点;我已经将我的int main和int getNextNumber包含在注释行中,我从函数返回一个值。

int getNextNumber(std::string& iExpression, int& ioLoopShift, bool& ioIsValidExpression)
{
    //spaces are ignored, a minus is a unary minus (so must be seated next to a number (no spaces between '-' and number))
    int length = iExpression.size(); //evaluate only once
    bool unaryMinusFound = false;
    bool numberFound = false;

    int oSubExpression = 0;
    for(int i =0; i < length; i++)
    {
        if((int)iExpression[i] == 32)
        {
            if(!numberFound)
            {
                if(!unaryMinusFound)
                {
                    continue;
                }
                else
                {
                    ioIsValidExpression = false;
                    td::cout << "address of ioIsValidExpression: " << &ioIsValidExpression << ", value: " << ioIsValidExpression << "\n";
                    return 0;
                }
            }
            else
            {
                return unaryMinusFound? -1 * oSubExpression: oSubExpression;
            }
        }
        if((int)iExpression[i] == 45 && !unaryMinusFound)
        {
            unaryMinusFound = true;
            continue;
        }
        if((int)iExpression[i] >= 48 && (int)iExpression[i] <= 57)
        {
            numberFound = true;
            oSubExpression = (int)(iExpression[i]-48) + 10*oSubExpression;
            ioLoopShift++;
            continue;
        }
        else
        {
            //garbage characters
            ioIsValidExpression = false;
            return 0;
        }
    }
    return unaryMinusFound? -1 * oSubExpression: oSubExpression;
}

int main:

int main(int argc, char* argv[])
{
    std::string test = " - 45 & ";
    int test2 = 0;
    bool test3 = true;
    std::cout << getNextNumber(test,test2,test3) << ", address of test3: " << &test3 << ", value: " << test3 << "\n";

    return 0;
}

运行程序的输出:

address of ioIsValidExpression: 0xbf86e58f, value: 0
0, address of test3: 0xbf86e58f, value: 1

1 个答案:

答案 0 :(得分:4)

未指定函数参数(以及输出语句是函数链)的评估顺序。在输出整个事物之前,将函数的结果保存在变量中,考虑它是如何正常工作的:test

int temp = getNextNumber(test, test2, test3);
std::cout << temp << ", address of test3: " << &test3 << ", value: " << test3 << "\n";

输出:

  

ioIsValidExpression的地址:0xbfaa85cf,值:0
  0,test3的地址:0xbfaa85cf,值:0