c++ - 如何区分 LineSegment 类和 Line 类?

标签 c++ class

我使用两个 Point 来定义一个 Line 和一个 LineSegment,例如:

class Point { ... };
class Line
{
  Point p1, p2;
  //...
};
class LineSegment
{
  Point p1, p2;
  //...
};

LineSegmentLine 的定义相同,所以我一开始使用了typedef Line LineSegment 而不是定义另一个LineSegment类。但是很快,我发现我无法定义函数distance来计算点与线或点与线段之间的距离。

class Point { ... };
class Line
{
  Point p1, p2;
  //...
};
typedef Line LineSegment;
double distance(const Point& a, const Line& b) { ... }
double distance(const Point& a, const LineSegment& b) { ... }

肯定会出现编译错误。

所以,我的问题是:是否有更好的方法来区分 LineLineSegment 而无需重新定义 LineSegment

最佳答案

我听从了@Amadan 的建议。创建一个抽象类。

#include <iostream>

struct Point { int x, y; };
struct AbstractLine { Point p1, p2; };
struct Line : AbstractLine { };
struct LineSegment : AbstractLine { };

void distance(const Point& a, const Line& b)
{
  std::cout << "void distance(const Point& a, const Line& b)" << std::endl;
}
void distance(const Point& a, const LineSegment& b)
{
  std::cout << "void distance(const Point& a, const LineSegment& b)" << std::endl;
}
int main()
{
  Point p;
  Line a;
  LineSegment b;
  distance(p, a);
  distance(p, b);
}

关于c++ - 如何区分 LineSegment 类和 Line 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17583470/

相关文章:

c# - 无法在 C# 中创建两个具有相同名称的属性

java - 获取匿名内部类的Class<?>对象

objective-c - Objective-C中的类构成问题: Is it possible to inherit a class variable?

c++ - 如何在 C++ 中将 std::wstring 转换为 LPCTSTR?

c++ - 打印所有可能有 4 个字母的单词的时间太多

c++ - 干净地抑制 gcc 的 `final` 建议警告 (`-Wsuggest-final-types` 和 `-Wsuggest-final-methods` )

java - 有人怎么会意外地在 Java 中启动一个类呢?

ruby-on-rails - 我如何知道 rail html.erb 组件的 ID 和类是什么?

c++ - 通过引用调用 `constexpr` 成员函数 - clang vs gcc

c# - 如何从 C# 使用 : Expose C++ data structures/types (structs, 枚举?