【发布时间】:2017-02-03 07:22:06
【问题描述】:
我一直在尝试理解 C++ 中的类型转换。在下面的代码中,B类是A类的子类,两者共享多态关系。
#include <iostream>
using namespace std;
class A{
int a;
public:
virtual void sayhello() {cout<<"Hello from A"<<endl;}
};
class B:public A{
int b;
public:
void sayhello(){cout<<"Hello from B"<<endl;}
void another_func(){cout<<"Hello from B::another_func"<<endl;}
};
int main() {
A *temp1 = new A;
//Statement 1
B *b =(B*) temp1;
//Statement 2
//B* b = dynamic_cast<B*>(temp1);
b->another_func();
delete temp1;
return 0;
}
上述程序的输出 -
Hello from B::another_func
我很难理解以下问题 -
1) For statement 1我们如何将父对象转换为子对象。逻辑上这应该是不正确的,因为现在我们已经扩展了这个对象的能力(同一个对象现在可以访问子类函数another_func)。
Java 中的类似代码会产生错误 -
"不兼容的类型:A不能转换为B
B b = (A)温度;"
现在,如果我们注释语句 1 并取消注释语句 2,语句 2 会发生类似的情况。
那么,为什么 C++ 允许这样做呢?
2) 现在,如果我们从两个类中删除 sayhello() 函数,使得它们不具有多态关系,则作为 dynamic_cast 的语句 2 不再起作用(正如我们所知,dynamic_cast 可以向下转换多态类),而是语句 1 的 c 样式转换仍然产生相同的输出。
所以我们可以说c风格的转换不是基于类之间的多态关系。
c-style cast 发生的参数是什么?
【问题讨论】:
-
您的程序调用了未定义的行为。几乎任何事情都可能发生;标准的夸张是the computer is allowed to make demons fly out your nose。