(注意:相应的要点可用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
的 operator()
被调用,而不是 MySphere
的。
如何拥有v[0]
调用MySphere::operator()
?
最佳答案
由于您将 Function
对象放入 vector 中,因此有 object slicing ,你根本做不到。虚函数需要指针或引用才能正确使用继承树。
我能给的唯一建议是重新考虑您的设计。
关于c++ - 派生类调用父类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39065192/