c++ - 派生类调用父类的方法

标签 c++ cgal

(注意:相应的要点可用here。)


我有许多派生自 std::unary_function<K::Point_3, K::FT> 的方法加上 typedef K::Point_3 Point; (底层库 CGAL 需要它)- 该类称为 Function .

我现在需要将派生类的一些实例(示例:MySphere)添加到 Function_vector 中:

#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Implicit_to_labeling_function_wrapper.h>

typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef K::FT FT;

class Function: public std::unary_function<K::Point_3, K::FT>
{
public:
  typedef K::Point_3 Point; // necessary
  // I'd rather not define operator() here
  virtual K::FT operator()(K::Point_3 p) const {return 0.0;}
};

class MySphere: public Function
{
public:
  virtual K::FT operator()(K::Point_3 p) const {return 3.14;}
};

typedef CGAL::Implicit_multi_domain_to_labeling_function_wrapper<Function>
                                               Function_wrapper;
typedef Function_wrapper::Function_vector Function_vector;

int main()
{
  MySphere f1;

  Function_vector v;
  v.push_back(f1);

  std::cout << f1(CGAL::ORIGIN) << std::endl; // MySphere::operator()
  std::cout << v[0](CGAL::ORIGIN) << std::endl; // Function::operator() :(

  return 0;
}

问题:

Function_vector不接受指针,所以实际上是抽象的 Function类不能是虚拟的,需要实现 operator()来自 std::unary_function .添加 MySphere 时实例到 Function_vector , MySphere被投入 FunctionFunctionoperator()被调用,而不是 MySphere的。

如何拥有v[0]调用MySphere::operator()

最佳答案

由于您将 Function 对象放入 vector 中,因此有 object slicing ,你根本做不到。虚函数需要指针或引用才能正确使用继承树。

我能给的唯一建议是重新考虑您的设计。

关于c++ - 派生类调用父类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39065192/

相关文章:

c++ - 从点集重建 CGAL 表面

c++ - CGAL新手---入门难点: CGAL_Qt5 Returns FALSE in CMake

c++ - 具有 C++ 代码生成和 doxygen 支持的免费 UML 工具

c++ - 表示平面图/GIS 拓扑 : ArcObjects vs. CGAL 安排

c++ - 尝试使用 std::get_time 解析 YYMMDD 并失败

c++ - 用 'this' 指针初始化 std::array

c++ - Windows 7 上的 Cygwin G++ 链接器(ld.exe)找不到 libc.so.6 和其他库文件

c++ - CGAL组合 map 和Geomview

python - 使用 CGAL 创建六面体并使其相交

c++ - 如何使用 CGAL 存储折叠的边缘