gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:52:29 26 4
gpt4 key购买 nike

假设我已经设置了这段代码:

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 告诉我我正在访问错误数据。我总能得到正确答案,但这让我很烦。我试图停止使用堆栈分配的参数,但我无法重载任何指针操作。对于这些类的用户,是否有任何无指针或友好的方式?

最佳答案

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

将其展开以使其更明显:

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

f 现在包含对由 Polynomial({1,2}) 和 Polynomial({3,2}) 创建的临时变量的引用。

您可能需要考虑使用 std::function<double(double)>对象和 lambda,像这样:

#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;
}

关于c++ - C++复合设计模式中的操作重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26050170/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com