如何在基本类型参考中存储对派生类型的参考
How to store reference to a derived type in the base type reference?
考虑:
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;
我知道这不是您在问题的标题中实际要求的 - 但是如前所述,您都不能这样做。
不知道为什么您需要对指针进行引用,因此很难建议另一种方法。
相关文章:
- 为什么"fun(i)"被推导出为"fun<int&>"而不是"fun<int>",因为"i"是"int"的类型而不是参考?
- 不能使这种类型的"void(C::* volatile)(int) const "在参考手册C++示
- 返回int数据类型v/s传递参考
- 将参考类型作为嵌套模板结构中的模板参数作为模板参数不起作用
- 如何检查两种类型是否相同,忽略const和参考
- CPP中的单个参考代表两种或多个数据类型
- const自动参考绑定到(NULL)指针 - 实际类型是什么
- 维护对元素参考类型
- 为什么可以将其他类型变量用作C 中常量参考参数参数的参数
- 在编写特征以进行参考和非参考类型时,如何减少重复
- Python ctypes,回调函数增强类型是C++参考
- 通过参考推断模板包中的冲突类型
- 如何使用自我参考类型并在C 类中使用别名
- 如何在基本类型参考中存储对派生类型的参考
- 试图分配输出以查看指针和参考输出时,请勿命名类型错误
- 了解普遍参考的类型扣除
- sizeof参考对于类型和数据成员的不同
- 参考类型静态数据成员的问题可能是编译器错误
- 比较C 中的自动和参考类型
- 初始化C 的参考类型