本文介绍了我有点困惑。在C ++中,您可以分配指向基类的派生类的地址吗?反过来怎么样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1。你可以将派生类的对象的地址分配给指向基类的指针吗?



2.你能指定一个基类对象的地址吗?指向派生类的指针?



我尝试过:



我试着读一本充满错误和令人困惑的解释的书。

1. Can you assign the address of an object of a derived class to a pointer to the base class?

2. Can you assign the address of an object of a base class to a pointer to the derived class?

What I have tried:

I tried reading a book full of errors and confusing explanations.

推荐答案


BaseClass* pBase = ....;
DerivedClass* pDerived = dynamic_cast<derivedclass*> (pBase);
if (pDerived != 0)
{
   // yes - pBase was really pointing to a DerivedClass object
   // an now we can use pDerived to access the derived class's members
   .....
}


这篇关于我有点困惑。在C ++中,您可以分配指向基类的派生类的地址吗?反过来怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 05:50