c++ - C++ 中的调度表

标签 c++ c dispatch-table

假设我有如下内容:

class Point : geometry {
   ...
   Point(double x, double y) {
   }
   double distanceTo(Line) {
   }
   double distanceTo(Point) {
   }
}
class Line : geometry {
   ...
   Line(double x, double y, double slopex, double slopey) {
   }
   double distanceTo(Line) {
   }
   double distanceTo(Point) {
   }
}
struct point_t {
    double x, y;
}
struct line_t {
    double x, y, slope_x, slope_y;
}
struct Geom_Object_t {
   int type;
   union {
       point_t p;
       line_t l;
   } geom;
}

我想知道为像这样的函数定义调度表的最佳方法是什么

double distanceTo(Geom_Object_t * geom1, Geom_Object_t * geom2) {
}

这些类是用 C++ 编写的,但是 distanceTo 函数和结构必须外部为 C

谢谢

最佳答案

我会让类图有所不同:抽象基类 GeomObject,子类 geometry(使用 getType 访问器,以及纯虚拟 distanceTo 重载),以及 GeomObject 的具体子类 LinePoint(具有访问器和重载的覆盖) . "extern C" double distanceTo 函数的需要不是问题,因为无论如何您都不是在谈论该函数的重载:您只是想返回 geom1.distanceTo(x)(让虚拟表完成那部分工作;-)其中 x 是适当的转换,例如,假设我已经解释过的类图:

extern "C"
double distanceTo(Geom_Object_t * geom1, Geom_Object_t * geom2) {
  if(geom2->getType() == POINT_TYPE) {
    return geom1->distanceTo(static_cast<Point*>(geom2));
  } else {
    return geom1->distanceTo(static_cast<Line*>(geom2));
  }
}

关于c++ - C++ 中的调度表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2076238/

相关文章:

从文本文件创建二维 double 组

c++ - MouseHook 检测鼠标何时移动

c - 基本C指针问题

c++ - 如何将特征雅可比 SVD 与特征仿射矩阵一起使用

c - 如何使用定义预处理器来定义函数指针?

c - 什么是调度表?我如何在 C 中实现它?

在 C 中跨多个源文件创建调度表注册函数

c++ - 在调度表中的类外使用模板类方法

c++ - 我想在 CentOS 7 上安装 clang-tidy 作为 c++ 的 linter,但找不到包

c++ - 如何在QWebEngine中设置QNetworkCookieJar?