I spent around two hours on that problem, and I have visited these stackoverflow questions before:
c++ passing a const object reference to a function
Passing const& as a function argument
both did not help me, so I am specifying my problem here:
1) I have a class Polygon that stores Point2Ds in a list. The class has among others two member functions:
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) The class also contains a struct Triple that is the return value of the function findClosestPts. I need that, because the function needs to return two points and one distance:
struct Tripel {
Point2D pt1;
Point2D pt2;
float dist;
};
The problem is now in the implementation of Polygon.cpp. This is my (current) code for the two above mentioned functions:
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 {
...
}
The compiler error is:
error: non-member function 'const Tripel& findClosestPts(...)' cannot have cv-qualifier
So I guess I am not allowed to make this function const, because it returns a struct. Is that true?
Anyways, I changed the function signature to this:
Tripel const& findClosestPts (std::vector<Point2D> const& P,
std::vector<Point2D> const& X,
std::vector<Point2D> const& Y);
So, the function is not const anymore. This leads to the following compiling error:
error: passing 'const Polygon' as 'this' argument of 'const Tripel& Polygon::findClosestPts(...)' discards qualifiers [-fpermissive]
I do not know, what to do now. I tried pretty much everything, deleting all the const statements, changing them around, making findClosestPts public, making it const again, making the three std::vectors const before passing them into the other function … but everything leaded to (different) compiling errors.
So my question is, how do I need to write the two functions, to achieve the following: I want to have a function closestPoints() that is a public member function and that returns the pair of the two closest points. For that it needs an auxilary, private member function findClosestPts(vector1, vector2, vector3) that returns the above mentioned struct Triple?
I would be happy about help, because I am stucked here since a while :/
You can make it
const, you just forgot to qualify the name in the implementation.