派生类调用父方法

时间:2016-08-21 14:18:15

标签: 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会被投放到Function,而Function的{​​{1}}被调用,而不是{{1} }}的

如何operator()致电MySphere

2 个答案:

答案 0 :(得分:3)

由于您将Function对象放入向量中,因此具有object slicing,因此您无法做到。虚函数需要指针或引用才能正确使用继承树。

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

答案 1 :(得分:0)

作为一种解决方法,可以创建另一个包装器MyFun并将其输入Functionàla

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

#include <memory>

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

class MyFun: public std::unary_function<K::Point_3, K::FT>
{
  public:
  virtual K::FT operator()(K::Point_3 p) const = 0;
};

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

class Function: public std::unary_function<K::Point_3, K::FT>
{
  public:
  typedef K::Point_3 Point;

  explicit Function(std::shared_ptr<MyFun> fun):
    fun_(fun)
  {
  }

  virtual K::FT operator()(K::Point_3 p) const {
    return fun_->operator()(p);
  }

  private:
  std::shared_ptr<MyFun> fun_;
};


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

int main()
{
  auto f1 = std::make_shared<MySphere>();

  Function_vector v;
  v.push_back(Function(f1));

  std::cout << (*f1)(CGAL::ORIGIN) << std::endl;
  std::cout << v[0](CGAL::ORIGIN) << std::endl;

  return 0;
}
相关问题