C ++在函数参数中转换指向基类指针的引用

时间:2020-12-12 21:39:53

I'm trying to create the constructor of a nested class, which inherits from a parent nested class, using its constructor. Basically:

我正在尝试使用其构造函数创建嵌套类的构造函数,该类从父嵌套类继承。基本上:

DerivedList<T>::DerivedNested::DerivedNested(DerivedNode*& ptr)
  : BaseList<T>::BaseNested::BaseNested(ptr)
{}

The prototype of the constructor of my BaseNested goes like this:

我的BaseNested的构造函数的原型是这样的:

BaseList<T>::BaseNested::BaseNested(BaseNode*& ptr)

(and is required to get the ptr parameter by reference since it needs the address of said pointer in its code)

(并且需要通过引用获取ptr参数,因为它需要代码中所述指针的地址)

I figured I had to cast my DerivedNode* to a BaseNode*, but : a static_cast::BaseNode*>(ptr) finds no matching functions since it isn't a reference, and a static_cast::BaseNode*&>(ptr) gives an invalid cast error.

我想我必须将DerivedNode *转换为BaseNode *,但是:static_cast :: BaseNode *>(ptr)找不到匹配的函数,因为它不是引用,而static_cast :: BaseNode *&>(ptr)给出了无效的演员错误。

The same goes for dynamic_cast. A reinterpret_cast compiles, but gives something incorrect during excecution.

dynamic_cast也是如此。 reinterpret_cast会编译,但在执行期间会出现错误。

Does anyone know how I could call that parent constructor?

有谁知道如何调用该父构造函数?

1 个解决方案

#1


4  

If you think you need a reference, that's probably because you want to modify the pointer later. The problem is that the type of the pointer in the derived class is DerivedNode*, and BaseNode* in the base class. What if the base class affects a DerivedNode2* to its pointer ?

如果您认为需要引用,那可能是因为您想稍后修改指针。问题是派生类中的指针类型是DerivedNode *,而基类中的BaseNode *。如果基类影响DerivedNode2 *到它的指针怎么办?

You should use setters, or move the logic from the base class to the derived ones.

您应该使用setter,或将逻辑从基类移动到派生类。

#1


4  

If you think you need a reference, that's probably because you want to modify the pointer later. The problem is that the type of the pointer in the derived class is DerivedNode*, and BaseNode* in the base class. What if the base class affects a DerivedNode2* to its pointer ?

如果您认为需要引用,那可能是因为您想稍后修改指针。问题是派生类中的指针类型是DerivedNode *,而基类中的BaseNode *。如果基类影响DerivedNode2 *到它的指针怎么办?

You should use setters, or move the logic from the base class to the derived ones.

您应该使用setter,或将逻辑从基类移动到派生类。