我可以使用对派生 class 实例的基础 class 引用来初始化派生 class 引用吗?
Can I Initialize a derived class reference with a base class reference to derived class instance?
我有如下内容:
class A { ... };
class B : public A { ... };
// ...
B b;
const A& aref(b);
// ...
const B& bref(aref);
当我编译时,我得到:
no suitable user-defined conversion from "const A" to "const B" exists
现在,如果这些是指针而不是引用,我会使用
bptr = dynamic_cast<B*>(aptr);
但参考文献中没有。我应该怎么办?切换到指针?还有别的吗?
您可以使用 dynamic_cast
作为引用,它们只是抛出异常而不是在失败时返回 nullptr
:
try {
const B& bref(dynamic_cast<const B&>(aref));
}
catch (const std::bad_cast& e) {
//handle error
}
如果你完全知道aref
实际上是一个B
,那么你可以static_cast
:
const B& bref(static_cast<const B&>(aref));
我有如下内容:
class A { ... };
class B : public A { ... };
// ...
B b;
const A& aref(b);
// ...
const B& bref(aref);
当我编译时,我得到:
no suitable user-defined conversion from "const A" to "const B" exists
现在,如果这些是指针而不是引用,我会使用
bptr = dynamic_cast<B*>(aptr);
但参考文献中没有。我应该怎么办?切换到指针?还有别的吗?
您可以使用 dynamic_cast
作为引用,它们只是抛出异常而不是在失败时返回 nullptr
:
try {
const B& bref(dynamic_cast<const B&>(aref));
}
catch (const std::bad_cast& e) {
//handle error
}
如果你完全知道aref
实际上是一个B
,那么你可以static_cast
:
const B& bref(static_cast<const B&>(aref));