【发布时间】:2015-03-15 01:53:13
【问题描述】:
我正在构建一个需要处理几何图形的 C++ 程序。我一直试图让boost::geometry 工作,但我遇到了以下问题。我的观点需要维护一个 ID 值或其他识别标签(我需要将它们链接到存储在其他对象中的属性)。我可以使用BOOST_GEOMETRY_REGISTER_POINT_2D_GET_SET 成功注册此点并执行boost::geometry 操作,但是当我对其执行任何操作时boost::geometry 似乎创建了我的点的新副本而没有id 值。
使用带有自定义点的boost::geometry 是否有什么我遗漏的东西可以做我想做的事情,还是我必须重新考虑我的方法并找到其他方法来做我想做什么?
以下代码显示了一个示例点类(int id 是标识符)以及一个编译和运行的代码示例(带有适当的#include 和namespace 声明)但是它不断删除我的点 ID:
点类:
class My_Point
{
public:
My_Point(const My_Point &p);
My_Point(double x = 0.0, double y = 0.0, int new_id = 0);
const double Get_X() const;
const double Get_Y() const;
void Set_X(double new_x);
void Set_Y(double new_y);
const int Get_ID() const;
void Set_ID(int new_id);
private:
int id;
double x;
double y;
}
复制构造函数:
My_Point::My_Point(const My_Point &p) {
Set_X(p.Get_X());
Set_Y(p.Get_Y());
Set_ID(p.Get_ID());
}
测试代码:
void TestPolygon()
{
vector < My_Point > p;
p.push_back(My_Point(0.0, 0.0, 0));
p.push_back(My_Point(1.0, 0.0, 1));
p.push_back(My_Point(1.0, 1.0, 2));
p.push_back(My_Point(0.0, 1.0, 3));
p.push_back(My_Point(0.0, 0.0, 4));
cout << "Initial points are:\n";
for (int i = 0, n = p.size(); i < n; i++)
{
cout << point_to_string(p.at(i)) << "\n";
}
detect_enter();
polygon<My_Point> poly;
append(poly, p);
//this code gives each point with an incorrect id of 0
cout << "Polygon points are:\n";
for (int i = 0, n = poly.outer().size(); i < n; i++)
{
cout << point_to_string(poly.outer().at(i)) << "\n";
}
detect_enter();
strategy::transform::rotate_transformer<degree, double, 2, 2> rotate(45.0);
for (int i = 0, n = poly.outer().size(); i < n; i++)
{
transform(poly.outer().at(i), poly.outer().at(i), rotate);
}
vector<My_Point> p2;
p2 = poly.outer();
//this code gives an incorrect id of 0.
cout << "Final points are:\n";
for (int i = 0, n = p2.size(); i < n; i++)
{
cout << point_to_string(p2.at(i)) << "\n";
}
detect_enter();
//this code gives the correct id values as expected.
cout << "Original points were:\n";
for (int i = 0, n = p.size(); i < n; i++)
{
cout << point_to_string(p.at(i)) << "\n";
}
}
【问题讨论】:
-
你的复制构造函数是做什么的?
-
感谢尼尔的提问。复制构造函数代码为: My_Point::My_Point(const My_Point &p) { Set_X(p.Get_X()); Set_Y(p.Get_Y()); Set_ID(p.Get_ID()); }
-
如果您所做的只是直接复制,则不应提供复制构造函数。它会自动生成一个。
-
谢谢尼尔 - 如果我注释掉复制构造函数,我仍然有同样的问题,所以这不是问题所在。另外,我显然没有使用 Stack Overflow 的评论格式的窍门,但我无法让我之前评论中的代码正确格式化......
-
“另外,我显然还没有掌握使用 Stack Overflow 的评论格式的窍门……” - 您应该将相关信息添加到您的问题中。您可以通过单击编辑链接来做到这一点。
标签: c++ boost boost-geometry