2010-04-02 68 views
4

包括

#include <functional> 

using namespace std; 

int main() { 
    binary_function<double, double, double> operations[] = { 
    plus<double>(), minus<double>(), multiplies<double>(), divides<double>() 
    }; 
    double a, b; 
    int choice; 
    cout << "Enter two numbers" << endl; 
    cin >> a >> b; 
    cout << "Enter opcode: 0-Add 1-Subtract 2-Multiply 3-Divide" << endl; 
    cin >> choice; 
    cout << operations[choice](a, b) << endl; 
} 

,我得到的错误是:std :: binary_function - 呼叫不匹配?

Calcy.cpp: In function ‘int main()’: 
Calcy.cpp:17: error: no match for call to ‘(std::binary_function<double, double, double>) (double&, double&)’ 

任何人都可以解释为什么我收到此错误,以及如何摆脱它?

回答

6

std::binary_function只包含参数和返回类型的typedef。它从来没有打算作为一个多态的基类(即使它是,你仍然有切片问题)。

作为替代方案,你可以使用boost::function(或std::tr1::function)是这样的:

boost::function<double(double, double)> operations[] = { 
    plus<double>(), minus<double>(), multiplies<double>(), divides<double>() 
}; 
+0

为什么不能编译器标志上'主()'的第一行的错误?如果该数组定义是允许的,那么应该是对存储在数组中的函数的调用。为什么那个错误呢? – 2010-04-02 17:44:01

+5

它只是做你需要它做的事情。 'binary_function'(或者对于标准库中任何其他类型而言是重要的)不适合编译器的特殊处理。由于'plus' ...从'binary_function'继承了赋值是正确的,所以你得到了切片。编译器无法编译最后一行,因为在binary_function中未定义'double operator()(double,double)',就像调用通过基类派生类中添加的任何方法将失败一样... – 2010-04-02 17:49:07

+0

@David:好吧,我现在明白了。谢谢。发布它作为答案,我会接受它。 – 2010-04-02 17:58:31