复合函数调用和独立函数调用之间的不同行为?

时间:2013-02-11 03:29:03

标签: c++ operator-overloading

下面的代码编译并运行完美。但是,如果我更换行

int d=xgcd(x,y,&m,&n);
cout<<d << " = "<<m<<" * "<<x<<" + "<<n<<" * "<<y<<endl;

    cout<< xgcd(x,y,&m,&n) << " = "<<m<<" * "<<x<<" + "<<n<<" * "<<y<<endl;

然后,mn将为零,而不是它们应该是什么。所以我想知道这种行为差异背后的原因是什么。我错过了什么吗?

这是用C ++编写的代码,我使用带有标志-O0的gcc 4.72。


testXGCD.cpp:

#include"xgcd.h"
#include<iostream>
#include<cstdlib>
using namespace std;
int main(int argc, char** argv) {
    // Read the command line parameter
    int x=atoi(argv[1]), y=atoi(argv[2]);
    int m=0,n=0;
    int d=xgcd(x,y,&m,&n);
    // Output the result;
    cout<<d << " = "<<m<<" * "<<x<<" + "<<n<<" * "<<y<<endl;
}

xgcd.h:

#ifndef XGCD
#define XGCD
#include<vector>
    // Perform the extended Euclidean Algorithm.
    // Find (m,n) and return it. pp and qp are two pointers to store the
    // coefficients of m and n so 1 = pm + qn.
    const int xgcd(int m, int n, int* pp = 0, int* qp = 0) {
        // The temp variable to store the remainder.
        int temp;
        // Create a container to store the quotients.
        std::vector<int> quotients;
        // Start the Euclidean algorithm.
        while(!(m==0)) {
        // store the quotient for the extended Euclidean algorithm.
            quotients.push_back(n/m);
            temp = m;
            m = n%m;
            n = temp;
        }
        // Before performing the magic pattern Bud Brown showed us in class, 
        // put base value 0 and 1 to the end.
        quotients.back() = 1;
        quotients.push_back(0);
        // Create an iterator to traverse the quotients and do the trick.
        typename std::vector<int>::reverse_iterator rip = quotients.rbegin();
        rip+=2;
        // Do the trick here!
        while(rip!=quotients.rend()) {
            *rip=*rip * *(rip-1) + *(rip-2);
            rip++;
        }
        // If there are odd number of quotients, the last value should be
        // it's negative. Otherwise, the second last value should be negative.
        if(quotients.size() % 2) {
            if(pp!=0)
            *pp=-quotients[0];
            if(qp!=0)
            *qp=quotients[1];
        }else{
            if(pp!=0)
            *pp=quotients[0];
            if(qp!=0)
            *qp=-quotients[1];
        }
        return temp;
    }
    #endif

我使用头文件而不是c文件用于xgcd.h,因为我修改了原始模板实现,并且不打算为我的作业问题创建另一个单独的实现文件。

有谁知道为什么会有这样的差异?

0 个答案:

没有答案