如何将结构转换为其基类型之一?
在c#中,你可以使用关键字"as"来做到这一点Entity as Monster.我怎么能用c ++做到这一点?
这是我的结构:
struct Entity
{
USHORT X;
USHORT Y;
UINT Serial;
USHORT SpriteID;
};
struct Monster : Entity
{
UINT UNKNOWN;
BYTE Direction;
USHORT Type;
};
struct Item : Entity
{
BYTE UNKNOWN1;
USHORT UNKNWON2;
};
struct NPC : Entity
{
UINT UNKNOWN1;
BYTE Direction;
BYTE UNKNOWN2;
BYTE NameLength;;
byte Name[];
};
Run Code Online (Sandbox Code Playgroud)
在C++中,这种可能性仅存在于指向多态类型对象的指针(即具有至少一个虚函数的类型).你可以用一个dynamic_cast<PtrType>.
这是一个完整的例子(也在ideone上):
#include <iostream>
using namespace std;
struct A {virtual void foo(){}};
struct B {virtual void foo(){}};
int main() {
A *a = new A();
B *b = new B();
A *aPtr1 = dynamic_cast<A*>(b);
cout << (aPtr1 == 0) << endl; // Prints 1
A *aPtr2 = dynamic_cast<A*>(a);
cout << (aPtr2 == 0) << endl; // Prints 0
delete a;
delete b;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
第一个dynamic_cast失败,因为b指向一个与之不兼容的类型的对象A*; 第二个dynamic_cast成功.
| 归档时间: |
|
| 查看次数: |
157 次 |
| 最近记录: |