【发布时间】:2015-01-16 15:29:36
【问题描述】:
为什么我不能将派生类的指针转换为指向基类的指针?
struct Base { };
struct Derived : Base { };
int main()
{
Derived* derived = nullptr;
static_cast<Base*&>(derived);
}
我明白了:
invalid static_cast from type 'Derived*' to type 'Base*&'
【问题讨论】:
-
首先,
static_cast无效,因为您没有将返回值存储在任何地方。其次,如果你想将Derived*变量转换为Base*变量,那么去掉&。 -
所以它应该类似于
Base* base = static_cast<Base*>(derived);。但是,根据您当前的代码,您似乎可以简单地执行Base* base = nullptr;,因为转换Derived*变量不会改变它的值。 -
这是一个学术问题,还是你真的需要这个演员阵容?
-
不,这不是一个学术问题。我需要调用一个函数作为参数
Base*&。
标签: c++ pointers casting reference