C ++中复合设计模式中的操作重载

时间:2014-09-26 00:23:11

标签: c++ operator-overloading composite

假设我已经设置了所有代码:

class Function
{
public:
    virtual double eval(double x) const =0;
};

class Polynomial : public Function
{
private:
    std::vector<double> coefficients;
public:
    // ...
};

class CompositeFunction : public Function
{
private:
    char operation;
    Function* left;
    Function* right;
public:
    // ...  
};

CompositeFunction operator+(Function& f, Function& g) {
    return CompositeFunction('+',&f,&g);
}

现在,我尝试做以下事情:

CompositeFunction f = Polynomial({1,2}) + Polynomial({3,2});
printf("%lf\n",f.eval(1));

我没有得到任何编译错误但是当我尝试评估f时,Valgrind告诉我我正在接收不良数据。我总能得到正确的答案,但这让我很烦恼。 我试图停止使用堆栈分配的参数,但我无法重载任何指针操作。 对于这些类的用户,是否有任何无指针方式或友好的方式?

1 个答案:

答案 0 :(得分:0)

这是因为f引用了两个临时对象。

将其展开以使其更加明显:

CompositeFunction f = operator+( Polynomial({1,2}), Polynomial({3,2}) );

f现在包含对多项式({1,2})和多项式({3,2})创建的临时数的引用。

您可能需要考虑使用std::function<double(double)>个对象和lambdas,如下所示:

#include <iostream>
#include <functional>
#include <vector>

typedef std::function<double(double)> Function;

Function polynomial(std::vector<double> const &coefficients) {
    return [coefficients](double x) {
        return x * coefficients[0]; // dummy evaluation
    };
}

Function add(Function f1, Function f2) {
    return [f1, f2](double x) { return f1(x) + f2(x); };
}

int main() {
    Function f = add(polynomial({3,4}), polynomial({1,2}));
    std::cout << f(3.3) << std::endl;
}

这是std :: shared_ptr:

#include <iostream>
#include <functional>
#include <memory>
#include <vector>

class Function
{
public:
    virtual double eval(double x) const = 0;
    virtual double derivative(double x) const = 0;
    virtual ~Function() {}
};
typedef std::shared_ptr<Function> FunctionPtr;

class Polynomial : public Function
{
private:
    std::vector<double> coefficients;
public:
    // ...
    Polynomial(std::vector<double> c) : coefficients(c) {}
};

class CompositeFunction : public Function
{
private:
    char operation;
    FunctionPtr left;
    FunctionPtr right;
public:
    // ...
    CompositeFunction(FunctionPtr l, FunctionPtr r) : operation('+'), left(l), right(r) {}
};

FunctionPtr operator+(FunctionPtr f, FunctionPtr g) {
    return std::make_shared<CompositeFunction>(f, g);
}

int main() {
    auto p1 = std::make_shared<Polynomial>(std::vector<double>{1.0, 2.0});
    auto p2 = std::make_shared<Polynomial>(std::vector<double>{3.0, 4.0});
    auto f = std::make_shared<CompositeFunction>(p1, p2);
    auto f2 = p1 + p2;
    std::cout << f2->eval(3.3) << std::endl;
    std::cout << f2->derivative(3.3) << std::endl;
}