gpt4 book ai didi

c++ - 在返回结构的函数中传递值 - const 错误

转载 作者:太空狗 更新时间:2023-10-29 23:28:35 38 4
gpt4 key购买 nike

我在那个问题上花了大约两个小时,之前我已经访问过这些 stackoverflow 问题:

c++ passing a const object reference to a function

Passing const& as a function argument

两者都没有帮助我,所以我在这里说明我的问题:

1) 我有一个 Polygon 类,它在列表中存储 Point2D。该类有两个成员函数:

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(),它是一个公共(public)成员函数并返回对最近的两个点。为此,它需要一个辅助的私有(private)成员函数 findClosestPts(vector1, vector2, vector3) 来返回上面提到的 struct Triple?

如果有帮助我会很高兴,因为我被困在这里有一段时间了:/

最佳答案

可以让它成为const,你只是忘了在实现中限定名称。

          //class name
||
\/
Tripel const& Polygon::findClosestPts (std::vector<Point2D> const& P,
std::vector<Point2D> const& X, std::vector<Point2D> const& Y) const

关于c++ - 在返回结构的函数中传递值 - const 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10048676/

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