如何使用抽象类型的C++指针指向具体类?

How to use a C++ pointer of abstract type to point to a concrete class?

本文关键字:指针 C++ 抽象 何使用 抽象类 类型      更新时间:2023-10-16

我正在使用点云库,我试图避免重复以下行为:

pcl::PointCloud<pcl::PointXYZRGB>::Ptr filter(PointCloud<pcl::PointXYZRGB>::Ptr input_cloud) {
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_filtered(new pcl::PointCloud<pcl::PointXYZRGB>);
subclass.setInputCloud(input_cloud);
subclass.filter(*cloud_filtered);
return cloud_filtered;
}

我希望使用基于此示例的内容,并遵循以下行

pcl::Filter<PointXYZRGB>* f;
pcl::Subclass<PointXYZRGB> s; //where s is an implementation of f
f = &s;
pcl::PointCloud<pcl::PointXYZRGB>::Ptr filter(PointCloud<pcl::PointXYZRGB>::Ptr input_cloud) {
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_filtered(new pcl::PointCloud<pcl::PointXYZRGB>);
f->setInputCloud(input_cloud);
f->filter(*cloud_filtered);
return cloud_filtered;
}

但是,这不会像编译器报告的那样f does not name a type编译。

我假设这是由于 pcl::filter 是一个抽象类吗?

这种方法是否适用于示例类(如 pcl::VoxelGrid),或者是否有替代方案?

任何帮助都非常感谢!

应在函数中移动到f = &s;行。

在本例中,它被移动到派生子类的构造函数中。

感谢对用户,aschepler 的回答