gpt4 book ai didi

c++ - apply_visitor 不改变对象

转载 作者:行者123 更新时间:2023-11-28 01:29:41 25 4
gpt4 key购买 nike

我继承自boost::static_visitor<>并定义了一个类如下:

class move_visitor : public boost::static_visitor<> {

private:

double m_dx, m_dy;

public:

move_visitor() : m_dx(0.0), m_dy(0.0) {}
move_visitor(double dx, double dy) : m_dx(dx), m_dy(dy) {}
~move_visitor() {}

void operator () (Point &p) const {
p.X(p.X() + m_dx);
p.Y(p.Y() + m_dy);
}

void operator () (Circle &c) const {

Point center_point(c.CentrePoint().X() + m_dx, c.CentrePoint().Y() + m_dy);
c.CentrePoint(center_point);
}

void operator() (Line &l) const {
Point start(l.Start().X() + m_dx, l.Start().Y() + m_dy),
end(l.End().X() + m_dx, l.End().Y() + m_dy);

l.Start(start);
l.End(end);

}
};

这个类应该改变一些对象,点,线和圆的 x 和 y 位置。

当我执行以下代码时:

int main()
{

typedef boost::variant<Point, Line, Circle> ShapeType;

Point p(1, 2);
Line l(p, p);
Circle c(p, 5);

ShapeType shape_variant;

std::cout << p << "\n\n"
<< l << "\n\n"
<< c << "\n\n";

shape_variant = p;
boost::apply_visitor(move_visitor(2, 2), shape_variant);

std::cout << p << std::endl;

shape_variant = l;
boost::apply_visitor(move_visitor(2, 2), shape_variant);
std::cout << std::endl << l << std::endl;

return 0;
}

p保持为 1、2,l 也是如此.为什么我的对象在“apply_visitor”之后没有改变?

最佳答案

您正在修改 shape_variant,而不是 pl

尝试

std::cout << boost::get<Point>(shape_variant) << std::endl;

std::cout << boost::get<Line>(shape_variant) << std::endl;

关于c++ - apply_visitor 不改变对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52142667/

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