如何在基本类型参考中存储对派生类型的参考

How to store reference to a derived type in the base type reference?

本文关键字:参考 类型 存储 派生      更新时间:2023-10-16

考虑:

struct Base{};
struct Derived: Base{};
int main() {
    Derived *d{};
    Base *&b = d; // Error: non-const reference to rvalue. 
    (void)b; 
    return 0;
}

正如评论所示,分配试图存储非cont的引用对rvalue。我知道RVALUE是d转换为Base *。但是我如何解决这个问题,因此我可以通过分配给b来更改d

以说明为什么它是一个问题,想象您有另一个结构

struct OtherDerived : Base
{};

现在考虑如果您在b

定义后添加以下行会发生什么
b = new OtherDerived();

此(如果允许)必须将d(类型派生*)分配给另一个有效的*,这是无效的。

要解决此问题,您可以确定您引用的指针是否真的需要是派生指针。如果不是,则可以是基本指针,并且您对基本指针的引用是可以的。

Derived *d{};
Base* pointerToABase = d;
Base*& refToAPointerToABase = pointerToABase;

否则,如果您引用的指针必须是派生的*不是基础*,则可以更改参考的类型:例如用。

替换B的声明
    Derived*& refToAPointerToADerived = d;

我知道这不是您在问题的标题中实际要求的 - 但是如前所述,您都不能这样做。

不知道为什么您需要对指针进行引用,因此很难建议另一种方法。