简体   繁体   English

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

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

I'm working with the Point Cloud Library and I'm trying to avoid repeating the following behaviour: 我正在使用点云库,并且正在尝试避免重复以下行为:

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;
}

I hoped to use something based on this example and along the lines of: 我希望基于此示例并遵循以下方法使用:

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;
}

However this will not compile as f does not name a type as reported by the compiler. 但是,由于f does not name a type编译器报告f does not name a type ,因此f does not name a type编译。

I assume is this due to pcl::Filter being an abstract class? 我认为这是由于pcl :: Filter是一个抽象类吗?

Is this approach valid for an example class such as pcl::VoxelGrid or is there an alternative? 这种方法对诸如pcl :: VoxelGrid的示例类有效吗?还是有替代方法?

Any help is much appreciated! 任何帮助深表感谢!

The line f = &s; f = &s; should be moved to within a function. 应该移到函数内。

In this case it was moved to within the constructors of derived subclasses. 在这种情况下,它被移到派生子类的构造函数中。

Credit and thanks for the answer to user, aschepler 感谢并感谢用户aschepler的回答

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM