Visual C++ .NET/Development/Pointer
Версия от 15:31, 26 мая 2010; (обсуждение)
Convert Between Class Pointers
#include "stdafx.h"
#using <mscorlib.dll>
using namespace System;
class BaseClass { virtual void F(){} };
class DerivedClass : public BaseClass {};
int main(void)
{
DerivedClass* a = new DerivedClass;
BaseClass* b = dynamic_cast<BaseClass*>(a);
if (b != 0)
Console::WriteLine("Conversion to base class successful.");
else
Console::WriteLine("Conversion to base class unsuccessful.");
delete a;
return 0;
}
Convert Between Class References with dynamic_cast
#include "stdafx.h"
#include <typeinfo.h>
#using <mscorlib.dll>
using namespace System;
class BaseClass { virtual void F(){} };
class DerivedClass : public BaseClass {};
int main(void)
{
DerivedClass a;
DerivedClass& aa = a;
BaseClass& b = dynamic_cast<BaseClass&>(aa);
Console::WriteLine("Conversion to base class successful.");
return 0;
}
Convert Between Pointers and Numbers with reinterpret_cast
#include "stdafx.h"
#using <mscorlib.dll>
using namespace System;
int main(void)
{
char* pStr = "A";
int* pInt = reinterpret_cast<int*>(pStr);
Console::WriteLine("As string: ");
Console::WriteLine(pStr);
Console::WriteLine("As integer: ");
Console::WriteLine(*pInt);
return 0;
}