【发布时间】:2012-04-20 09:04:15
【问题描述】:
我在这个问题上花了大约两个小时,我之前访问过这些 stackoverflow 问题:
c++ passing a const object reference to a function
Passing const& as a function argument
两者都没有帮助我,所以我在这里说明我的问题:
1) 我有一个类Polygon,它将Point2Ds 存储在一个列表中。该类有两个成员函数:
public:
std::pair<Point2D,Point2D> closestPts() const;
private:
Tripel const& findClosestPts (std::vector<Point2D> const& P,
std::vector<Point2D> const& X,
std::vector<Point2D> const& Y) const;
2) 该类还包含一个struct Triple,它是函数findClosestPts 的返回值。我需要那个,因为函数需要返回两个点和一个距离:
struct Tripel {
Point2D pt1;
Point2D pt2;
float dist;
};
问题现在出现在 Polygon.cpp 的实现中。这是我上面提到的两个函数的(当前)代码:
std::pair<Point2D,Point2D> Polygon::closestPts() const {
...
int size = m_points.size();
std::vector<Point2D> P (size);
std::vector<Point2D> X (size);
std::vector<Point2D> Y (size);
...
// some manipulation of the vectors, filling them with Point2D
// at this point, I have three non-const std::vector<Point2D>
// try to call the other function
Tripel closPts = findClosestPts(P, X, Y);
...
}
Tripel const& findClosestPts (std::vector<Point2D> const& P, std::vector<Point2D> const& X, std::vector<Point2D> const& Y) const {
...
}
编译错误是:
error: non-member function 'const Tripel& findClosestPts(...)' cannot have cv-qualifier
所以我想我不能创建这个函数const,因为它返回一个struct。这是真的吗?
无论如何,我将函数签名更改为:
Tripel const& findClosestPts (std::vector<Point2D> const& P,
std::vector<Point2D> const& X,
std::vector<Point2D> const& Y);
所以,函数不再是const。这会导致以下编译错误:
error: passing 'const Polygon' as 'this' argument of 'const Tripel& Polygon::findClosestPts(...)' discards qualifiers [-fpermissive]
我不知道,现在该怎么办。我几乎尝试了所有方法,删除所有 const 语句,更改它们,使 findClosestPts 公开,再次使其成为 const,在将三个 std::vectors 传递给另一个函数之前使它们成为 const ......但一切都导致(不同)编译错误。
所以我的问题是,我需要如何编写这两个函数来实现以下目标:我想要一个函数closestPoints(),它是一个公共成员函数,它返回两个最近点的对。为此,它需要一个辅助的私有成员函数findClosestPts(vector1, vector2, vector3),它返回上面提到的struct Triple?
我会很高兴得到帮助,因为我被困在这里已有一段时间了:/
【问题讨论】:
-
您确定要返回 const 引用吗?这很容易导致悬空引用。
Triple似乎无论如何都是一个值类型。 -
困惑:是
Triple===Tripel吗? -
@Robᵩ 我很确定他们的意思是一样的?英语与德语。 ;-)
-
哦,是的……那是一个错字;)是的,你猜对了我的国籍:)