通过C 中的构造函数将地址参数传递给基类指针



我正在使用从基类继承的抽象类型指针。

当前,每个子类必须在其构造函数中包括以下行为:

p = &f; //where p is the inherited pointer and f is the subclass filter

自然,我希望将这种行为转移到基础上,但我正在努力获得这项工作。我不确定这是我如何宣布类型的方式,还是我需要更改实现以反映行为的运动(或其他!(。

我本质上尝试复制此行并通过子类构造函数调用基本构造函数:

//base.h
class Base {
    pcl::Filter<pcl::PointXYZRGB>* f;
    public:
        Base(pcl::Filter<pcl::PointXYZRGB> abs_filter);
};
//base.cpp
Base::Base(pcl::Filter<pcl::PointXYZRGB> abs_filter) { f = &abs_filter; }
//subclass.h
class Subclass: public Base {
    pcl::VoxelGrid<pcl::PointXYZRGB> vg;
    public:
        Subclass(void);
};
//subclass.cpp
Subclass::Subclass(void): Base(vg) { }

这不会编译并产生以下错误:

error: cannot declare parameter ‘abs_filter’ to be of abstract type ‘pcl::Filter<pcl::PointXYZRGB>’

我试图使用地址pcl::Filter<pcl::PointXYZRGB> &abs_filter并将方法更改为f = abs_filter;,但这也没有编译,报告以下内容:

error: cannot convert ‘pcl::Filter<pcl::PointXYZRGB>’ to ‘pcl::Filter<pcl::PointXYZRGB>*’ in assignment Base::Base(pcl::Filter<pcl::PointXYZRGB> &abs_filter) { f = abs_filter; }

我在哪里做错了什么?

任何帮助都非常感谢!

定义具有按值传递的参数的函数时,这就是发生的

int myFun(myClass x) {
    // x exists only in this function
    // because is a copy of the argument passed to x
}

所以更改

Base(pcl::Filter<pcl::PointXYZRGB> abs_filter) { f = &abs_filter; }

to

Base(pcl::Filter<pcl::PointXYZRGB>& abs_filter) { f = &abs_filter; }

不要获取它的副本,以传递值本身。

您将F设置为指向局部变量的指针 - 它将无法使用(ABS_FILTER是VG -Variable的本地副本(。使用以下一项:

   Base::Base(pcl::Filter<pcl::PointXYZRGB>&abs_filter) { f = &abs_filter;}
   Base::Base(pcl::Filter<pcl::PointXYZRGB>*abs_filter) { f = abs_filter; }

(类中相应的更改(。

最新更新