具有相同功能名称的Segfault。为什么?怎么修?

时间:2012-11-15 08:02:32

标签: c++ segmentation-fault

我知道通过更改trig函数名称,我摆脱了segfault。但是,我并不完全清楚为什么。我的猜测是我在我的实现中得到了递归调用。有人可以在这里给出严格的解释吗?

此外,我愿意保持这种方式,因此我想知道应该添加/修改什么来保留我的功能名称。

P.S。:我知道这是一个愚蠢的问题,只是在这里开始使用c ++,所以请耐心等待。 :)

代码:

#include <iostream>
#include <string>
#include <cmath>

#define _USE_MATH_DEFINES

using namespace std;

/*
   Represents a calculator with various functions.
*/
class Calc {
public:
    //arithmetic functions
    static double sum(double a, double b){ return a+b; };
    static double subtract(double a, double b){ return a-b;};
    static double multiply(double a, double b){ return a*b; };
    static double divide(double a, double b){ if (b == 0) return b; return a/b; };
    static double avg(double a, double b){ return (a+b)/2; };

    //trigonometric funcitons
    static double sin(double x){ return sin(M_PI*x); };
    static double cos(double x){ return cos(M_PI*x); };
    static double tan(double x){ return tan(M_PI*x); };
};

void getValue(double *a){
    cout << "Please, enter a value: " << endl;
        cin >> (*a);
}

void getValues(double *a, double *b){
    cout << "Please, enter two values: " << endl;
        cin >> (*a) >> (*b);
}

bool getCommand(string *cmd){
    cout << "Please, enter a command (+,-,*,/,avg, sin, cos, tan, exit): ";
    cin >> (*cmd);
    if ( (*cmd) == "exit"){
        return false;
    } else {
        return true;
    }
}

int main (){
    string cmd;
    double a,b;

    while (getCommand(&cmd)){
        if (cmd == "sin" || cmd == "cos" || cmd == "tan"){
            getValue(&a);
            if (cmd == "sin"){
                cout << "Sine: " << Calc::sin(a) << endl;
            } else if (cmd == "cos"){
                cout << "Cosine: " << Calc::cos(a) << endl;
            } else if (cmd == "tan"){
                cout << "Tangent: " << Calc::tan(a) << endl;
            }
        } else {
            getValues(&a,&b);
            if (cmd == "+"){
                cout << "Summation: " << Calc::sum(a,b) << endl;
            } else if (cmd == "-"){
                cout << "Subtracttion: " << Calc::subtract(a,b) << endl;
            } else if (cmd == "*"){
                cout << "Multiplication: " << Calc::multiply(a,b) << endl;
            } else if (cmd == "/"){
                cout << "Division: " << Calc::divide(a,b) << endl;
            } else if (cmd == "avg"){
                cout << "Average: " << Calc::avg(a,b) << endl;
            }
        }
    }
    return 0;
}

2 个答案:

答案 0 :(得分:6)

你得到它,递归电话。我想你想要

static double sin(double x){ return ::sin(M_PI*x); };

使用范围解析运算符::将使sin函数调用全局sin函数,而不是递归调用你的函数。

顺便说一句,如果你想将度数转换为弧度,那么你实际上需要

static double sin(double x){ return ::sin((M_PI/180.0)*x); };

答案 1 :(得分:1)

1)您应该#define _USE_MATH_DEFINES 之前 #include <cmath>

2)你的Calc函数确实包含无限递归(它们自称为)。您需要按如下方式更改它们:

static double sin(double x){ return std::sin(M_PI*x); }

即,将呼叫限定为sin(),以明确表示您想要呼叫全局呼叫。