在我的示例中:
在向上转换时,第二个d.print()不应该调用print "base“吗?
它不是"d“派生对象向上转换为基类对象吗?
在向下预测方面,它有什么优势?
你能以一种实用的方式解释向上和向下吗?
#include <iostream>
using namespace std;
class Base {
public:
void print() { cout << "base" << endl; }
};
class Derived :public Base{
public:
void print() { cout << "derived" << endl; }
};
void main()
{
// Upcasting
Base *pBase;
Derived d;
d.print();
pBase = &d;
d.print();
// Downcasting
Derived *pDerived;
Base *b;
pDerived = (Derived*)b;
}发布于 2016-01-30 21:10:37
向上转换在C++中是隐式的,并且在处理虚拟调度时经常使用。换句话说,您有一个指向Base的指针,您可以从该指针访问整个类层次结构的公共接口,并且可以在运行时进行选择。这里假设您的接口函数被标记为virtual。示例:
Base* pBase;
cin >> x;
if(x == 0) // this is done at runtime, as we don't know x at compile time
pBase = new Derived1;
else
pBase = new Derived2;
pBase->draw(); // draw is a virtual member function在这些在运行时完成分派的情况下,它是非常有用的。简单地说,向上转换允许将派生类视为基类(通过其公共接口)。
向下转换的用处不大,应该尽可能避免使用IMO。一般来说,这是糟糕设计的标志,因为很少需要将Base对象转换为派生对象。可以通过dynamic_cast完成(并检查结果),如下所示
Base* pBase = new Derived; // OK, the dynamic type of pBase is Derived
Derived* pDerived = dynamic_cast<Derived*>(pBase);
if(pDerived) // always test
{
// success
}
else
{
// fail to down-cast
}This link为这个主题提供了一个非常有用的介绍。
https://stackoverflow.com/questions/35102079
复制相似问题