C ++程序中的奇怪错误

时间:2016-03-20 16:14:03

标签: c++ compiler-errors

所以我写了一个简单的计算器用于学习目的。但我不能让它工作,因为我得到一个奇怪的错误。我尽我所能,但我无法解决错误。请看一下并告诉我。

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;

double add (double x, double y)
{
double addition = x+y;
return addition;
}
double sub (double x ,double y)
{
double subtraction = x-y;
return subtraction;
}
double mul (double x , double y)
{
double multiplication = x*y;
return multiplication;
}
double div (double x, double y)
{
double division = x/y;
return division;
}
int main ()
{
int x; int y; int op;
cout << "Enter a number: ";
cin >> x;
cout << "Enter second number: ";
cin >> y;
cout << "1: Addition,   2: Subtraction, 3: Multiplication,  4: Division" <<   endl;
cout << "What operation you want: ";
cin >> op;
switch (op)
{
case 1:
cout << x << " + " << y << " = " <<  add(x, y);`enter code here`
break;

case 2:
cout << x << " - " << y << " = " << sub(x,y);
break;

case 3:
cout << x << " * " << y << " = " << mul (x,y);
break;
case 4:
cout << x << " / " << y << " = " << div (x,y);
break;
default:
cout << "Invalid operation"
}

}

1 个答案:

答案 0 :(得分:4)

因为您使用了

using namespace std;

您与标准函数div发生冲突。具体来说,因为存在重载std::div_t div( int x, int y );并且你用两个整数调用div,所以会调用它。

一般情况下,请避免在代码中使用using namespace std;

在这种情况下,最简单的解决方法是以不同的方式命名函数:

double divide(double x, double y)
{
    double division = x/y;
    return division;
}

由于没有stdlib重载需要两个双打,你也可以做这样的事情,让编译器使用你的函数:

div(static_cast<double>(x),static_cast<double>(y));

另一种方法是将您的函数放入命名空间:

namespace ops {
double div(double x, double y) {
    double division = x/y;
    return division;
}
} // namespace ops

...

cout << x << " / " << y << " = " << ops::div(x,y);