C++到C#的"As"?
c++ to c#'s "As"?
如何将结构体强制转换为其基类型之一?
在c#中,你可以像Entity as Monster
一样使用关键字"as"。我如何在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[];
};
在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;
}
第一个dynamic_cast
失败,因为b
指向的对象类型与A*
不兼容;第二个dynamic_cast
成功
看看c++类型强制转换操作符:
http://www.cplusplus.com/doc/tutorial/typecasting/Entity e;
Monster m = static_cast<Monster>(e);
如果实体至少有一个虚方法,你可以这样做:
Monster * m = dynamic_cast<Monster*>(&e); // m != null if cast succeed
注意c#的"as"不能在struct
上工作。在这种情况下,你必须在c#中强制转换对象,这相当于c++中的static_cast
。
如果转换无效,程序将无法编译。
相关文章:
- 为什么我会" void value not ignored as it ought to be"?
- 为什么 std::shared_ptr 被认为是"heavy"和"expensive",但 std::array "same perfprmance as plain (c-style) arrays
- 了解 Linux 虚拟内存:valgrind 的 massif 输出显示了有和没有 --pages-as-heap 的主要差异
- 编译错误:"lvalue required as left operand of assignment" 不确定原因
- 如何理解"Temporary objs are destroyed as the last step in evaluating the full-expression"?谁能用一些简单的例子来说明这
- Atom gpp编译器给出"'C:UsersadminUser' is not recognized as an internal or..."错误
- r-在Rcpp和C++之间转换矢量(使用Rcpp::as或Rcpp:::wrap)是否会创建一个新的矢量并复制元素
- template<class T, int N> void h(T const(&)[N]); as friend function
- 我正在"void value not ignored as it ought to be"我该怎么办?
- "expression cannot be used as a function"回报声明
- OMNeT++ cPacket as std::bitset 以应用 Reed-Solomon 编码
- 函数如何在不这样做的情况下在新线程上运行"as if"?
- C++指针算术"lvalue required as left operand of assignment"错误
- 当调用时,为什么ranges ::累积的init as std :: Move(init)
- 如何在开关语句中使用 cin "as a parameter"
- regex_match as predicate
- 类型转换运算符重载与 as 非成员函数
- 我在 MinGW 和 VS 代码"g++ not recognized as a cmdlet..."时遇到构建错误
- SpinBoxDelegate displayed as a DoubleSpinBoxDelegate
- 在 Rcpp 中调用'as'没有匹配函数