0

我想创建一个表达式结构来计算值(通过调用 operator().

expr - 基本表达式类,它应该像 result = expression(100500) 一样工作。const_value - 结构返回常量值。参数 - 返回它的参数(== 函数 ID)。e_add, prod, sub, ... - 不同的功能。

为什么代码调用基类 operator(),但忽略派生结构?

输出:

EXPR::operator() called
EXPR::operator() called

201000
const_value 1 called arg = 100
1

完整源代码:

#include <iostream>
#include <cmath>

using namespace std;

struct expr {
    virtual double operator()(double) {
        cerr << "EXPR::operator() called\n";
        return 100500;
    };
};

struct const_value : public expr {
    double _value;
    const_value (double value = 0): _value(value) {};
    double operator()(double arg = 0) override {
        cout << "const_value " << _value << " called arg = " << arg << '\n';
        return _value;
    };
};

#define make_bin_op(_op_name, _op) struct e_##_op_name : public expr {     \
    expr _left;                                                            \
    expr _right;                                                           \
    e_##_op_name(expr left, expr right): _left(left), _right(right) {};    \
    double operator()(double arg) override {                               \
        return _left(arg) _op _right(arg);                                 \
    };                                                                     \
}

make_bin_op(add,  +);

#undef make_bin_op

int main()
{
    const_value c1{1};
    e_add e{c1, c1};

    cout << e(100) << endl;
    cout << c1(100) << endl;

    return 0;
}
4

0 回答 0