#include
#include
using namespace std;
class cbase
{
public:
cbase() { }
virtual ~cbase() { }
void mybase()
{
cout << "cbase::mybase" << endl;
}
};
class cderive : public cbase
{
public:
cderive() { }
~cderive() { }
void myderive()
{
cout << "cderive::myderive" << endl;
}
};
int main(void)
{
//上行的转换(派生类到基类的转换)
shared_ptr spderiveup;
shared_ptr spbaseup;
spderiveup = make_shared();
spbaseup = dynamic_pointer_cast(spderiveup);
spbaseup->mybase();
//下行的转换(基类到派生类的转换)
shared_ptr spderivedown;
shared_ptr spbasedown;
spbasedown = make_shared();
spderivedown = dynamic_pointer_cast(spbasedown);
if (spderivedown == null) //由于会进行类型的检查,这边是返回null
cout << "spderivedown is null" << endl;
/*
shared_ptr spderivedown;
shared_ptr spbasedown;
spbasedown = make_shared();
spderivedown = dynamic_pointer_cast(spbasedown);
if (spderivedown == null) //由于会进行类型的检查,这边是返回null
cout << "spderivedown is null" << endl;
spderivedown->myderive();
*/
return 0;
}
运行结果:
#include
#include
using namespace std;
class cbase
{
public:
cbase() { }
virtual ~cbase() { }
void mybase()
{
cout << "cbase::mybase" << endl;
}
};
class cderive : public cbase
{
public:
cderive() { }
~cderive() { }
void myderive()
{
cout << "cderive::myderive" << endl;
}
};
int main(void)
{
//上行的转换(派生类到基类的转换)
shared_ptr spderiveup;
shared_ptr spbaseup;
spderiveup = make_shared();
spbaseup = dynamic_pointer_cast(spderiveup);
spbaseup->mybase();
//下行的转换(基类到派生类的转换)
/*
shared_ptr spderivedown;
shared_ptr spbasedown;
spbasedown = make_shared();
spderivedown = dynamic_pointer_cast(spbasedown);
if (spderivedown == null) //由于会进行类型的检查,这边是返回null
cout << "spderivedown is null" << endl;
*/
shared_ptr spderivedown;
shared_ptr spbasedown;
spbasedown = make_shared();
spderivedown = dynamic_pointer_cast(spbasedown);
if (spderivedown == null) //由于会进行类型的检查,这边是返回null
cout << "spderivedown is null" << endl;
spderivedown->myderive();
return 0;
}
运行结果: