gpt4 book ai didi

重载运算符的 C++ 前向声明

转载 作者:行者123 更新时间:2023-11-28 02:42:07 24 4
gpt4 key购买 nike

我在论坛上发现了一个问题,我决定快速编写一个代码。我决定借此机会自学重载比较运算符。不幸的是,我似乎犯了一个错误。

我正在尝试与 Line 进行比较Quadrilateral 中的对象类(class)。我一直收到一个错误 Line是二元运算符的无效操作数 < .我尝试向前声明重载运算符,但这似乎没有帮助。谁能提出比较不起作用的原因?非常感谢任何帮助:)

(重载的运算符函数是代码中的最后一个函数,实际比较发生在Quadrilateral类)

#include <iostream>
#include <vector>
#include <cmath>

class Point {
private:
int x, y;
public:
Point(): x(0), y(0) {}
Point(int x, int y): x(x), y(y) {}

int getX() const { return x; }
int getY() const { return y; }

friend std::ostream& operator<<(std::ostream& stream, const Point& pt);

};

class Line {
private:
Point pt1, pt2;
public:
Line(): pt1(0,0), pt2(0,1) {}
Line(const Point& pt1, const Point& pt2): pt1(pt1), pt2(pt2) {}

friend auto operator<(const Line& ln1, const Line& ln2) -> bool;

friend std::ostream& operator<<(std::ostream& stream, const Line& ln);
};

class Quadrilateral {
private:
Point pt1, pt2, pt3, pt4;
public:
Quadrilateral(): pt1(0,0), pt2(0,1), pt3(1,0), pt4(1,1) {}
Quadrilateral(const Point& pt1, const Point& pt2,
const Point& pt3, const Point& pt4): pt1(pt1), pt2(pt2),
pt3(pt3), pt4(pt4) {}

auto getAllLines() const -> std::vector<Line> {
std::vector<Line> quadLines;
Line l1(pt1,pt2), l2(pt2,pt3), l3(pt3,pt4), l4(pt4,pt1);
quadLines.push_back(l1); quadLines.push_back(l2);
quadLines.push_back(l3); quadLines.push_back(l4);
return quadLines;
}

auto longestSide() const -> Line {
Line l1(pt1,pt2), l2(pt2,pt3), l3(pt3,pt4), l4(pt4,pt1);
return (l1 > l2 ? l1 : l2);
}

friend std::ostream& operator<<(std::ostream& stream, const Quadrilateral& q);

};

std::ostream& operator<<(std::ostream& stream, const Point& pt) {
stream << "(" << pt.x << ", " << pt.y << ")";
return stream;
}

std::ostream& operator<<(std::ostream& stream, const Line& ln) {
stream << ln.pt1 << " <-> " << ln.pt2 << std::endl;;
return stream;
}

std::ostream& operator<<(std::ostream& stream, const Quadrilateral& q) {
stream << q.pt1 << "\t" << " <-> " << "\t" << q.pt2 << "\n"
<< " ^" << "\t" << "\t" << " ^" << "\n"
<< " |" << "\t" << "\t" << " |" << "\n"
<< " v" << "\t" << "\t" << " v" << "\n"
<< q.pt4 << "\t" << " <-> " << "\t" << q.pt4 << "\n"
<< std::endl;
return stream;
}

auto operator<(const Line& ln1, const Line& ln2) -> bool {
double ln1_len = sqrt( pow((ln1.pt1.getX() - ln1.pt2.getX()),2) - pow((ln1.pt1.getY() - ln1.pt2.getY()),2) );
double ln2_len = sqrt( pow((ln2.pt1.getX() - ln2.pt2.getX()),2) - pow((ln2.pt1.getY() - ln2.pt2.getY()),2) );
return ln1_len < ln2_len;
}

最佳答案

我假设 return (l1 > l2 ? l1 : l2);导致错误。请注意,您使用的是 >在这里,但您只定义了 operator<() .

关于重载运算符的 C++ 前向声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25600469/

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