我使用两个 Point
来定义一个 Line
和一个 LineSegment
,例如:
class Point { ... };
class Line
{
Point p1, p2;
//...
};
class LineSegment
{
Point p1, p2;
//...
};
LineSegment
与Line
的定义相同,所以我一开始使用了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) { ... }
肯定会出现编译错误。
所以,我的问题是:是否有更好的方法来区分 Line
和 LineSegment
而无需重新定义 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/