gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:32:15 25 4
gpt4 key购买 nike

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

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

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

当然,我希望将此行为移至基类,但我正在努力完成这项工作。我不确定这是因为我声明类型的方式,还是我需要更改实现以反射(reflect)行为的移动(或其他原因!)。

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

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

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

不是获取它的拷贝,而是传递值本身。

关于c++ - 通过 C++ 中的构造函数将地址参数传递给基类指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43586974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com